By Rahul — Google Frontend Engineer
The Attack in Simple Terms
CSRF (Cross-Site Request Forgery) tricks your browser into making a request to a site where you are already logged in. The attacker does not need your password — they use the fact that your browser automatically sends cookies with every request.
How It Works
Real-World Example
In 2007, Gmail had a CSRF vulnerability. An attacker could create a page that, when visited by a Gmail user, would add email forwarding filters to forward all of the victim's email to the attacker.
Prevention Methods
1. CSRF Tokens (Most Common)
2. SameSite Cookies
Since Chrome 80 (2020), SameSite=Lax is the DEFAULT. This alone prevents most CSRF attacks.
3. Check Origin/Referer Headers
4. Custom Headers
Why SPA Frameworks Are Safer
React, Vue, and Angular apps typically use JSON APIs with custom headers (Authorization: Bearer token). Since tokens are in headers (not cookies), CSRF does not apply — the attacker cannot make the browser add the Authorization header automatically.
Best Practices
- Set
SameSite=LaxorStricton all cookies - Use CSRF tokens for any cookie-based authentication
- Prefer token-based auth (JWT in headers) for APIs
- Validate Origin header on the server
- Use POST for state-changing operations (never GET)
Summary
CSRF exploits the browser's automatic cookie sending. SameSite cookies are the easiest modern defense. CSRF tokens are the traditional approach. SPA frameworks with token-based auth are naturally resistant.