Web Fundamentals

Cross-Site Request Forgery (CSRF) Attacks

mediumWeb Fundamentals

Cross-Site Request Forgery (CSRF) Attacks

Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.

Topic content

TL;DRCSRF tricks authenticated users into performing unwanted actions. Protect with CSRF tokens + SameSite cookies.
High Signal
Google
Meta
Netflix
Agoda
30-Second Answerstart every interview with this

Cross-Site Request Forgery (CSRF) exploits a user's active session by tricking their browser into making unwanted requests to a trusted site. Prevention requires tokens, SameSite cookies, and protecting all state-changing endpoints.

The attacker tricks the victim's browser into signing a request (using the victim's valid session cookie) without their knowledge. The bank (server) accepts it because it looks legitimate.

1How CSRF Attacks Work

The attacker creates a malicious page that makes a request to the victim's authenticated site. The browser automatically includes cookies, making the request appear legitimate.

1. User logs into trusted site (bank.com) → Session cookie is set
2. User visits attacker's site (attacker.com)
3. Attacker's page auto-submits form or triggers request to bank.com
4. Browser sends request WITH cookies → Server processes it as valid

2CSRF Token Protection

Server generates a unique token per session, includes it in forms, and validates it on state-changing requests.

1. Server generates CSRF token and stores in session
2. Token is added as hidden field in forms
3. User submits form → Token sent with request
4. Server validates token matches session → Process request
5. Attacker cannot forge valid token
Key Takeaways
  • CSRF exploits authenticated sessions via forged requests
  • Always protect POST, PUT, DELETE, and PATCH endpoints
  • CSRF tokens are the most reliable defense
  • SameSite=Strict/Lax cookies provide strong additional protection
  • Use framework CSRF middleware when available
  • Never use GET for actions that change state