A user is logged into your shop in one tab. In another tab they open a link from a forum: a page of cat pictures. Hidden in that page is a form that posts to https://shop.example.com/account/email and submits itself on load. The browser dutifully attaches the user's session cookie, your controller sees an authenticated request, and the account email is now the attacker's. One "forgot password" later, the account is gone. Nobody stole a cookie or a password. The attacker just made the victim's browser send a request it was already allowed to send.
That is Cross-Site Request Forgery. It is old, it is well understood, and frameworks like Laravel block it by default, which is exactly why teams break it without noticing: a route added to the except list "temporarily", an SPA moved to another subdomain, a state-changing GET endpoint. Here is how the attack works, what each defence really does, and how to keep Laravel's protection intact in SPA setups.
How the Attack Works
CSRF relies on three facts:
- Browsers attach cookies to requests based on the destination, not on which site started the request (subject to SameSite, covered below).
- The server authenticates the request purely by that cookie.
- The attacker can predict every parameter of the request. There is nothing secret in "POST email=x to /account/email".
<!-- https://evil.example/cute-cats.html -->
<form id="f" action="https://shop.example.com/account/email" method="POST">
<input type="hidden" name="email" value="[email protected]">
</form>
<script>document.getElementById('f').submit();</script>
Note what the attacker cannot do: read the response. The same-origin policy blocks that. CSRF is a blind, write-only attack, which is why it targets state changes: change email, transfer money, add an admin, delete data. It also means CORS does not help: a form POST with a form content type is a "simple" request that is sent without any preflight.
Defence 1: Synchronizer Token
The classic fix breaks fact 3. The server stores a random token in the user's session and embeds it in every form. On each state-changing request it checks that the submitted token matches the session's token. The attacker's page cannot read your HTML (same-origin policy again), so it cannot learn the token, so its forged request fails.
In Laravel, the web middleware group runs VerifyCsrfToken (exposed as ValidateCsrfToken since Laravel 11) on every POST, PUT, PATCH and DELETE. It accepts the token from three places: the _token form field, the X-CSRF-TOKEN header, or the X-XSRF-TOKEN header (the encrypted value of the XSRF-TOKEN cookie). The @csrf Blade directive renders the hidden field:
<form method="POST" action="/account/email">
@csrf
<input type="email" name="email" required>
<button type="submit">Save</button>
</form>
<!-- @csrf renders: <input type="hidden" name="_token" value="..."> -->
A missing or wrong token produces a 419 Page Expired response. The comparison uses hash_equals(), and the token is regenerated on login via $request->session()->regenerate() plus regenerateToken() on logout, which also prevents session fixation.
Excluding routes is sometimes legitimate, for example a payment provider's webhook that has no session and is authenticated by an HMAC signature instead. Keep the list short and specific:
// bootstrap/app.php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(web: __DIR__.'/../routes/web.php')
->withMiddleware(function (Middleware $middleware): void {
// Only routes that are authenticated some other way, e.g. signed webhooks
$middleware->validateCsrfTokens(except: [
'webhooks/stripe',
]);
})
->create();
Defence 2: SameSite Cookies
SameSite breaks fact 1. A cookie with SameSite=Strict is never sent on requests initiated by another site. SameSite=Lax is sent on top-level GET navigations (clicking a link) but not on cross-site POSTs, iframes or fetch() calls. SameSite=None; Secure restores the old send-everywhere behaviour.
Chrome and Edge treat cookies without a SameSite attribute as Lax by default, and Laravel sets same_site to lax explicitly:
// config/session.php (trimmed)
return [
'driver' => env('SESSION_DRIVER', 'database'),
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'domain' => env('SESSION_DOMAIN'), // e.g. .example.com for SPA + API subdomains
'secure' => env('SESSION_SECURE_COOKIE'), // true in production
'http_only' => env('SESSION_HTTP_ONLY', true),
'same_site' => env('SESSION_SAME_SITE', 'lax'),
];
Lax stops the forged form POST above. But it is a second layer, not a replacement for tokens:
- "Site" is not "origin".
blog.example.comandshop.example.comare the same site. A vulnerable or user-content subdomain can CSRF its siblings with SameSite cookies attached. - GET is still sent. Any route that changes state on
GET(/logout,/cart/add?id=5,/newsletter/unsubscribe) remains forgeable with a plain link or<img>tag. - Browser differences. Older browsers ignore SameSite, and some browsers have special cases for recently set cookies.
Defence 3: Double-Submit Cookie
Some stateless backends cannot keep a token in a server session. The double-submit pattern puts a random value in a cookie and requires the client to echo it in a header or body field; the server only checks that both match. An attacker cannot read the cookie cross-site, so cannot copy it into the header.
The naive version has a hole: if an attacker controls any subdomain, they can write a cookie for the parent domain (cookie tossing) and then submit the matching value. The fix is the signed double-submit cookie: the token is nonce.HMAC(secret, session id + nonce), so a tossed cookie without the server secret, bound to the victim's session, is rejected. That is exactly what the challenge below asks you to build. Laravel's XSRF-TOKEN cookie is a variant of this: it is encrypted with APP_KEY and compared with the session token, so it cannot be forged either.
Laravel SPA Setups with Sanctum
For a first-party SPA on app.example.com calling api.example.com, Sanctum keeps cookie sessions and CSRF protection working across subdomains. The SPA first calls /sanctum/csrf-cookie, which sets the XSRF-TOKEN cookie; afterwards the HTTP client reads it and sends it back as X-XSRF-TOKEN.
import axios from 'axios';
export const api = axios.create({
baseURL: 'https://api.example.com',
withCredentials: true, // send the session cookie
withXSRFToken: true, // axios >= 1.6 only adds X-XSRF-TOKEN cross-origin when this is set
});
export async function login(email, password) {
await api.get('/sanctum/csrf-cookie'); // sets the XSRF-TOKEN cookie
await api.post('/login', { email, password });
}
Checklist for this setup: SANCTUM_STATEFUL_DOMAINS lists the SPA's domain, SESSION_DOMAIN=.example.com, config/cors.php has supports_credentials => true with an explicit origin, and $middleware->statefulApi() is enabled. If you use plain fetch(), read the XSRF-TOKEN cookie yourself, decodeURIComponent() it, and send it as X-XSRF-TOKEN.
Defence in Depth: Fetch Metadata
Modern browsers send Sec-Fetch-Site on every request: same-origin, same-site, cross-site or none (typed URL, bookmark). JavaScript cannot forge it. Rejecting cross-site writes is a cheap extra layer that also covers routes someone excluded from CSRF by mistake:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class RejectCrossSiteWrites
{
public function handle(Request $request, Closure $next): Response
{
if ($request->isMethodSafe()) {
return $next($request);
}
$site = $request->headers->get('Sec-Fetch-Site');
// Old browsers and non-browser clients do not send it: the CSRF token still applies.
if ($site !== null && ! in_array($site, ['same-origin', 'same-site', 'none'], true)) {
abort(403, 'Cross-site request blocked.');
}
return $next($request);
}
}
If your app never needs requests from sibling subdomains, drop same-site from the list to defend against the subdomain scenario too.
Testing CSRF Protection
One surprise first: Laravel's CSRF middleware skips verification when running unit tests, so a feature test posting without a token passes even if protection is configured correctly. That is convenient for normal tests and means you have to test your defences differently: test your own extra layers directly and assert that state-changing routes are not reachable over GET.
use App\Http\Middleware\RejectCrossSiteWrites;
use Illuminate\Support\Facades\Route;
beforeEach(function () {
Route::post('/_test/transfer', fn () => response()->noContent())
->middleware(RejectCrossSiteWrites::class);
});
it('blocks cross-site writes', function () {
$this->withHeader('Sec-Fetch-Site', 'cross-site')
->post('/_test/transfer')
->assertForbidden();
});
it('allows same-origin writes and clients without fetch metadata', function () {
$this->withHeader('Sec-Fetch-Site', 'same-origin')
->post('/_test/transfer')
->assertNoContent();
$this->post('/_test/transfer')->assertNoContent();
});
it('never changes state over GET', function () {
$this->get('/logout')->assertMethodNotAllowed();
$this->get('/account/delete')->assertMethodNotAllowed();
});
For the token check itself, an end-to-end test (Playwright or Dusk) that submits a form with the _token field removed and expects a 419 is the reliable proof.
Common Pitfalls
- State changes on GET. Logout links, "add to cart" links and one-click unsubscribe URLs bypass both tokens and SameSite=Lax. Use POST/DELETE.
- Growing
exceptlists. Every entry is a route with no CSRF protection. Only exclude routes authenticated by something other than cookies. - Token in the URL. Query strings end up in logs, history and
Refererheaders. Send tokens in a body field or header. - XSS defeats CSRF protection. Script running on your origin can read the token and send any request. CSRF defences assume you have no XSS.
- Login CSRF. Attackers can log the victim into the attacker's account and capture what they enter. Laravel protects the login form too; do not exclude it.
- Caching pages with tokens. A full-page cache that serves one user's HTML (and token) to everyone produces random 419s. Exclude forms or fetch the token separately.
- Assuming JSON APIs are immune. Endpoints that accept
text/plainor form bodies and parse them as JSON can be hit by simple requests.
When to Use What (and When Not To)
- Cookie-authenticated web app (Blade, Livewire, Inertia): keep Laravel's token check on, keep
same_site=lax, add fetch metadata if you like. This is the default and it is good. - First-party SPA with Sanctum: same protections, wired through
XSRF-TOKEN/X-XSRF-TOKEN. - Stateless backend with cookies but no session store: use a signed double-submit cookie.
- Pure bearer-token APIs (mobile apps, third parties sending
Authorizationheaders): CSRF does not apply, because the browser never attaches the credential automatically. Do not store those tokens in cookies, or you are back to needing CSRF protection. - Webhooks: exclude from CSRF and verify their HMAC signature instead.
CSRF is solved by default in Laravel. Your job is mostly to not un-solve it: no state changes on GET, a tiny except list, and the right cookie and Sanctum configuration when the frontend moves to another subdomain.
Try the challenge
Practice what you just learned. Write your solution, reveal hints if you get stuck.
Instructions
Implement CsrfGuard (PHP and Python), a signed double-submit cookie checker. The constructor takes a secret string and a random callable that returns a nonce string. issue(sessionId) gets one nonce from random and returns '<nonce>.<signature>', where signature is the lowercase hex HMAC-SHA256, keyed with secret, of the message '<len(sessionId)>!<sessionId>!<len(nonce)>!<nonce>' (lengths in bytes, e.g. '7!sess-42!5!n0nce'). validate(method, sessionId, cookieToken, submittedToken) returns true immediately for GET, HEAD and OPTIONS (case-insensitive). For any other method it returns false if either token is null/None, if the two tokens are not equal (compare in constant time), if the submitted token does not split on '.' into exactly two parts or the nonce part is empty, or if the signature part does not match the HMAC recomputed for this sessionId and nonce (constant-time compare). Otherwise it returns true.
Starter code
final class CsrfGuard
{
public function __construct(private string $secret, private Closure $random) {}
public function issue(string $sessionId): string
{
// TODO: nonce from $this->random, return "<nonce>.<hmac hex>"
throw new LogicException('TODO');
}
public function validate(string $method, string $sessionId, ?string $cookieToken, ?string $submittedToken): bool
{
// TODO: GET/HEAD/OPTIONS are always allowed
// TODO: both tokens present and equal (hash_equals)
// TODO: split "<nonce>.<signature>" and verify the HMAC for this session
throw new LogicException('TODO');
}
}
import hashlib
import hmac
from typing import Callable
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
class CsrfGuard:
def __init__(self, secret: str, random: Callable[[], str]) -> None:
self.secret = secret.encode()
self.random = random
def issue(self, session_id: str) -> str:
# TODO: nonce from self.random(), return "<nonce>.<hmac hex>"
raise NotImplementedError
def validate(self, method: str, session_id: str, cookie_token: str | None, submitted_token: str | None) -> bool:
# TODO: GET/HEAD/OPTIONS are always allowed
# TODO: both tokens present and equal (hmac.compare_digest)
# TODO: split "<nonce>.<signature>" and verify the HMAC for this session
raise NotImplementedError
Your solution
Hints
All hints revealedLength-prefixing the session id and nonce stops ambiguous concatenations like 'ab'+'c' vs 'a'+'bc'
The cookie and header must match AND the signature must be valid for the current session; one check alone is not enough
Use hash_equals() / hmac.compare_digest() for both comparisons
final class CsrfGuard
{
private const SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'];
public function __construct(private string $secret, private Closure $random) {}
public function issue(string $sessionId): string
{
$nonce = ($this->random)();
return $nonce.'.'.$this->sign($sessionId, $nonce);
}
public function validate(string $method, string $sessionId, ?string $cookieToken, ?string $submittedToken): bool
{
if (in_array(strtoupper($method), self::SAFE_METHODS, true)) {
return true;
}
if ($cookieToken === null || $submittedToken === null || ! hash_equals($cookieToken, $submittedToken)) {
return false;
}
$parts = explode('.', $submittedToken);
if (count($parts) !== 2 || $parts[0] === '') {
return false;
}
return hash_equals($this->sign($sessionId, $parts[0]), $parts[1]);
}
private function sign(string $sessionId, string $nonce): string
{
$message = strlen($sessionId).'!'.$sessionId.'!'.strlen($nonce).'!'.$nonce;
return hash_hmac('sha256', $message, $this->secret);
}
}
import hashlib
import hmac
from typing import Callable
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
class CsrfGuard:
def __init__(self, secret: str, random: Callable[[], str]) -> None:
self.secret = secret.encode()
self.random = random
def issue(self, session_id: str) -> str:
nonce = self.random()
return f"{nonce}.{self._sign(session_id, nonce)}"
def validate(self, method: str, session_id: str, cookie_token: str | None, submitted_token: str | None) -> bool:
if method.upper() in SAFE_METHODS:
return True
if cookie_token is None or submitted_token is None:
return False
if not hmac.compare_digest(cookie_token.encode(), submitted_token.encode()):
return False
parts = submitted_token.split(".")
if len(parts) != 2 or parts[0] == "":
return False
return hmac.compare_digest(self._sign(session_id, parts[0]), parts[1])
def _sign(self, session_id: str, nonce: str) -> str:
message = f"{len(session_id)}!{session_id}!{len(nonce)}!{nonce}"
return hmac.new(self.secret, message.encode(), hashlib.sha256).hexdigest()

