CSRF Tokens: How Cross-Site Request Forgery Protection Works
Cross-Site Request Forgery (CSRF) is one of the most common web security vulnerabilities, ranked consistently in the OWASP Top 10. CSRF tokens are the primary defense mechanism against these attacks, protecting users from unauthorized actions performed on their behalf.
Understanding CSRF Attacks
In a CSRF attack, a malicious website tricks a user's browser into making an authenticated request to a target website where the user is already logged in. Because the browser automatically includes cookies (including session cookies), the target server processes the request as if the user intentionally made it.
For example, if a user is logged into their bank account and visits a malicious site, an embedded image tag could trigger a transfer request: <img src="https://bank.com/transfer?to=attacker&amount=1000">
How CSRF Tokens Work
The server generates a unique, random token for each user session (or each form). This token is embedded in the HTML form as a hidden field and also stored server-side (typically in the session). When the form is submitted, the server compares the token from the form with the stored token. If they match, the request is legitimate.
The attack fails because the malicious site cannot read the CSRF token from the target site due to the Same-Origin Policy. Without the correct token, the forged request is rejected.
Implementation Approaches
- Synchronizer Token Pattern: Server generates token per session, embedded in forms
- Double Submit Cookie: Token set in both cookie and request body; server compares them
- Encrypted Token Pattern: Token contains user ID and timestamp, encrypted with server secret
- SameSite Cookie Attribute: Modern browsers block cross-site cookies with SameSite=Strict/Lax
CSRF in AJAX Requests
For single-page applications, the CSRF token is typically included as a custom header (e.g., X-CSRF-Token) or in the request body. The server validates this header on state-changing requests (POST, PUT, DELETE).
Conclusion
CSRF tokens remain an essential security measure. Combined with SameSite cookie attributes and proper CORS configuration, they provide robust protection against cross-site request forgery attacks.
