Cross-Site Request Forgery (CSRF): SameSite cookies, Double Submit Cookie pattern, and sync tokens.
How CSRF Operates
Cross-Site Request Forgery tricks an authenticated victim's browser into sending unauthorized commands to a vulnerable web application where the victim is already logged in (exploiting the browser's automatic credential submission).
1. Victim is logged into Bank (https://bank.com) with active session cookie.
2. Victim visits Malicious Site (https://evil.com).
3. Evil site contains hidden form:
<form action="https://bank.com/api/transfer" method="POST">
<input type="hidden" name="to" value="attacker_account" />
<input type="hidden" name="amount" value="10000" />
</form>
<script>document.forms[0].submit();</script>
4. Victim browser automatically attaches bank.com session cookie!
5. Bank transfers money unless protected by Anti-CSRF mechanisms!
1. First Line of Defense: SameSite=Lax / Strict Cookies
Modern browsers default to SameSite=Lax, which blocks cookies from being sent on cross-site POST/PUT/DELETE requests. For high-security applications, use SameSite=Strict.
2. The Double Submit Cookie Pattern (Stateless CSRF Defense)
For stateless REST APIs that cannot store server-side session tokens:
1. Server generates random CSRF token and sets it in an unreadable cookie:
Set-Cookie: __Host-csrf_token=abc123xyz; Path=/; Secure; SameSite=Lax
2. Frontend JavaScript reads CSRF token from a meta tag or response header.
3. On every state-changing request (POST/PUT/DELETE), the frontend sends the token
in a custom header:
X-CSRF-Token: abc123xyz
4. Server validates: does req.headers['x-csrf-token'] === req.cookies['__Host-csrf_token']?
Because of the Same-Origin Policy, evil.com cannot read the cookie or inject the custom header, completely thwarting the attack.