CSRF Defense: Tokens and SameSite Cookies
What You'll Learn
You'll learn the practical mechanisms to prevent CSRF attacks: synchronizer tokens, double-submit cookies, and the SameSite cookie attribute.
Core Defensive Techniques
Now that you understand how CSRF attacks exploit a user's authenticated session, let's explore the proven defenses that break the attacker's exploitation chain.
Synchronizer Token Pattern
The server generates a unique, unpredictable token for each user session and embeds it in forms or as a custom header. When the form submits, the server validates that the token matches. Since the attacker's malicious site can't read the token (thanks to the same-origin policy), they can't forge a valid request.
Think of it like a secret handshake: Your bank gives you a randomly-generated password good for just one transaction. The attacker doesn't know this password, so they can't make requests on your behalf.
Double-Submit Cookie Pattern
The server sets a random token in a cookie and requires the client to also include that same token in a request header or body parameter. The attacker can cause the browser to send cookies, but they can't read cookie values to duplicate them in the request body.
SameSite Cookie Attribute
This modern browser feature tells the browser: "Only send this cookie when requests originate from my own site." Setting SameSite=Strict or SameSite=Lax prevents the browser from attaching session cookies to cross-site requests, cutting off CSRF at the source.
Example: Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict
Defense in Depth
Combine these approaches: use SameSite cookies as your primary defense, add CSRF tokens for critical state-changing operations, and always validate the origin of requests.
Key Takeaway: Defend against CSRF by using unpredictable synchronizer tokens that attackers can't access, double-submit cookie patterns that exploit the same-origin policy, or SameSite cookie attributes that prevent browsers from sending authentication credentials on cross-site requests.