CSRF Protection — Auth

CSRF protection checks every request that changes data (POST, PUT, PATCH, DELETE); GET isn't checked, so a GET must never change data. Synchronizer token: a…

The browser attaches the session cookie to every request to portal.school.test, whoever asks it to. Even a form on another site can make Siti's browser send a POST, cookie and all. So a cookie on its own proves nothing.

That's why there is CSRF protection: a server-side check on every request that changes data. It checks not only "the session cookie is there", but also "this request really came from our own page". Picture a council office counter. The clerk recognises your face (that's the cookie), but still asks for the stamped form she handed you at the counter earlier (that's the CSRF token). A letter someone else sends in your name doesn't carry that form. How the attack works is covered in CSRF (Cross-Site Request Forgery) in the Security track. This lesson builds the check.

Which requests get checked

The rule starts with the HTTP method:

Synchronizer token: one token per session

The main pattern is the synchronizer token. When a session is created, the server makes a random token and stores it in the session. Every form carries that token in a hidden field. When the form comes back, the server compares the form's token with the session's. A page on another site cannot read the portal's pages (the browser's same-origin policy), so it never learns the token.

function issueCsrfToken(sessionId) {
  return "csrf_" + sessionId + "_n1"; // the exercise: a fixed "n1" nonce; really 32 random bytes
}

function validateCsrfToken(submittedToken, sessionToken) {
  if (!submittedToken || !sessionToken) return false; // empty, null, undefined: reject
  return submittedToken === sessionToken;
}

function isTrustedOrigin(origin, trustedOrigins) {
  if (!origin) return false; // no Origin: reject
  return trustedOrigins.includes(origin); // an exact match, not a "similar" one
}
Call Result
issueCsrfToken("sess42") "csrf_sess42_n1"
validateCsrfToken(token, token) true
validateCsrfToken("csrf_evil_n1", token) false, another session's token
validateCsrfToken(null, token) false
isTrustedOrigin("https://portal.school.test", TRUSTED) true
isTrustedOrigin("https://other-site.test", TRUSTED) false
isTrustedOrigin(null, TRUSTED) false

Origin and Sec-Fetch-Site: where the request came from

Modern browsers attach two headers a page cannot set: Origin on every POST, and Sec-Fetch-Site, which holds same-origin, same-site, cross-site or none (typed straight into the address bar). A hand-written middleware combines the origin check and the token check:

const TRUSTED = ["https://portal.school.test"];
const SAFE = ["GET", "HEAD", "OPTIONS"];

function checkCsrf(req, session) {
  if (SAFE.includes(req.method)) return "pass"; // only reading
  if (!isTrustedOrigin(req.headers.origin, TRUSTED)) return 403; // a foreign origin
  if (!validateCsrfToken(req.body._token, session.csrfToken)) return 403; // a wrong token
  return "pass";
}

SameSite=Lax: the first layer, not the only one

School Portal's session cookie is already SameSite=Lax. Now a form on https://calendar.school.test, another of the school's subdomains, sends a POST to https://portal.school.test/profile/email. Guess first: does Siti's session cookie go along or not?

Laravel sets same_site => 'lax' in config/session.php. With Lax, the browser leaves the cookie off a POST that comes from another site, but still sends it when the user clicks a link (a GET navigation). The key word is site: calendar.school.test and portal.school.test both sit under school.test, so they are one site, even though they are different origins. The request from the calendar is same-site, and Siti's session cookie goes along.

So SameSite holds back foreign sites, but not your own subdomains, and its rules differ a little between browsers. What rejects the calendar's request is the next check: its Origin isn't on the list, and the form doesn't have Siti's session token.

In Laravel 13: PreventRequestForgery

Laravel 13 calls the middleware PreventRequestForgery (its old names, VerifyCsrfToken and ValidateCsrfToken, remain as aliases). It is already in the web group, and its checks run in this order:

  1. Method GET, HEAD, OPTIONS: pass.
  2. The URI is on the exception list: pass.
  3. Sec-Fetch-Site: same-origin: pass. A request from the portal's own page in a modern browser is already safe here.
  4. The token matches the session's token (hash_equals): pass. The token is read from the _token field, the X-CSRF-TOKEN header, or the X-XSRF-TOKEN header.
  5. Anything else: 419, with the message CSRF token mismatch. for a JSON request, or the "Page Expired" page.
<form method="POST" action="/profile/email">
    @csrf {{-- becomes <input type="hidden" name="_token" value="..."> --}}
    <input name="email" type="email">
    <button>Save</button>
</form>
// bootstrap/app.php: excluded URIs, such as a webhook verified by its signature
->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: ['webhooks/*']);
})

Laravel's session token is 40 random characters. For a plain fetch, put csrf_token() in a <meta name="csrf-token"> tag and send it in the X-CSRF-TOKEN header.

Double-submit cookie for APIs

An API that logs in with a cookie, such as an SPA with Laravel Sanctum (the Auth in SPAs & Mobile Apps lesson), needs protection too. The pattern is the double-submit cookie: the server sets an XSRF-TOKEN cookie that JavaScript may read, the SPA copies its value into an X-XSRF-TOKEN header, and the server matches them. Another site can make the browser send the cookie, but can't read its value to put in a header. In Laravel the cookie holds the encrypted session token, so the server matches it against the session, not only against the cookie (axios does the copying automatically).

An API that uses only the Authorization: Bearer header needs no CSRF token at all: the browser never attaches that header on its own.

⚠️ Detours that slip past the CSRF check

TL;DR: CSRF protection checks every request that changes data (POST, PUT, PATCH, DELETE); GET isn't checked, so a GET must never change data. Synchronizer token: a random token per session in the form (@csrf becomes _token), compared with the session's token; reject null and the empty string, then ===. Origin check: Origin must exactly match the trusted list (null is rejected), and Sec-Fetch-Site says same-origin, same-site or cross-site. SameSite=Lax (Laravel's default) holds the cookie back on a POST from another site, but your own subdomains still get it. Laravel 13's PreventRequestForgery: GET passes, same-origin passes, a matching token passes, anything else is 419. An API with cookies uses double-submit (XSRF-TOKEN into X-XSRF-TOKEN); an API that uses only Authorization: Bearer needs no CSRF token.

⚡ A cookie alone proves nothing

Meaning: The browser attaches the session cookie to every request to the Portal, whoever asks it to. Even a form on another site can make Siti's browser send a POST, cookie and all. A CSRF token stops requests like that: sent from another origin without the user knowing, riding on a session cookie that is still active.

⚡ Only methods that change data are checked

Meaning: GET, HEAD, OPTIONS only read, so they aren't checked, on condition that a GET never changes data. POST, PUT, PATCH and DELETE are all checked.

⚡ The origin first, then the token

Write:

function checkCsrf(req, session) {
  if (SAFE.includes(req.method)) return "pass"; // only reading
  if (!isTrustedOrigin(req.headers.origin, TRUSTED)) return 403; // a foreign origin
  if (!validateCsrfToken(req.body._token, session.csrfToken)) return 403; // a wrong token
  return "pass";
}

Meaning: The token is random per session and travels in a hidden form field. A page on another site can't read the Portal's pages, so it never learns the token. Reject empty values first, then compare with ===.

⚡ SameSite=Lax is not enough

Guess first: a form on https://calendar.school.test sends a POST to https://portal.school.test/profile/email. Does Siti's session cookie (SameSite=Lax) go along?

It goes along. Both sit under school.test, so they are one site, even though they are different origins. What rejects it is the next check: its Origin isn't on the list, and the form doesn't have Siti's session token.

What you will learn