CSRF Protection Flow
Cross-Site Request Forgery (CSRF) is an attack where a malicious website tricks an authenticated user's browser into sending a state-changing request to another site where the user is logged in — exploiting the browser's automatic cookie sending behavior.
Cross-Site Request Forgery (CSRF) is an attack where a malicious website tricks an authenticated user's browser into sending a state-changing request to another site where the user is logged in — exploiting the browser's automatic cookie sending behavior.
The attack works because browsers automatically attach cookies to any request matching the cookie's domain, regardless of which site initiated the request. If a user is logged into bank.com and visits a malicious page, that page can silently submit a form or trigger a fetch to bank.com/transfer?amount=1000&to=attacker. The browser attaches the user's session cookie, and the bank server sees an authenticated request.
The classic defense is the synchronizer token pattern. The server generates a random, unpredictable CSRF token tied to the user's session and embeds it in every HTML form as a hidden field (or exposes it via a meta tag / cookie for AJAX use). When the form is submitted, the server validates that the submitted CSRF token matches the one it issued. A cross-origin attacker cannot read the CSRF token from the HTML (blocked by same-origin policy), so they cannot include a valid token in their forged request.
For AJAX-heavy applications, a common pattern is the double-submit cookie: the server sets a CSRF token as a readable (non-HttpOnly) cookie, and JavaScript reads it and includes it as a request header (e.g., X-CSRF-Token). The server validates that the header value matches the cookie. Cross-origin requests cannot set or read this custom header.
Modern applications can also rely on SameSite=Lax or SameSite=Strict cookies, which prevent cookies from being sent on cross-site POST requests entirely. This is now the browser default and provides strong CSRF protection without explicit tokens for most workflows. See Secure Cookie Flow for SameSite configuration details.