Cross-Site Request Forgery (CSRF): Modern Defense Strategies with SameSite and Tokens
How malicious websites hijack authenticated browser sessions, and how to stop them using SameSite cookies and Anti-CSRF tokens.
1. The Anatomy of a CSRF Attack
Imagine a user is logged into their banking portal at `bank.com`. Without logging out, they visit an untrusted forum containing an embedded malicious image or script.
The malicious page includes a hidden form targeting `https://bank.com/transfer` and automatically submits it via JavaScript. Because the user is logged in, their browser attaches the session cookie, and the bank processes the fraudulent transfer.
2. The Modern Shield: SameSite Cookie Attribute
The introduction of the `SameSite` cookie attribute revolutionized web security.
`SameSite=Strict`: Cookies are never sent in cross-site requests (e.g., following a link from an external email will require logging in again).
`SameSite=Lax`: Cookies are withheld on cross-site subrequests (such as images or fetch calls), but allowed when navigating via top-level link clicks. This is the modern recommended default.
# Recommended secure session cookie header configuration
Set-Cookie: session_id=abc123xyz789; Secure; HttpOnly; SameSite=Lax; Path=/;3. The Synchronizer Token Pattern
For maximum protection, applications generating server-rendered forms must embed a unique, cryptographically random anti-CSRF token into forms and validate it on the server before mutating state.
<!-- HTML Form with CSRF Token -->
<form action="/settings/change-email" method="POST">
<input type="hidden" name="csrf_token" value="d8e2a1b9c3f4e5a6" />
<input type="email" name="new_email" value="[email protected]" />
<button type="submit">Save Settings</button>
</form>4. Protecting Single Page Applications (SPAs) and APIs
When web applications use decoupled REST/GraphQL APIs with JWTs stored in memory and sent via `Authorization: Bearer <token>`, cross-origin forms cannot forge requests because browsers cannot inject custom HTTP headers without CORS preflight approval.