Cross-Site Request Forgery (CSRF) Attacks
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.
2CSRF Token Protection
Server generates a unique token per session, includes it in forms, and validates it on state-changing requests.
| Property | CSRF Token | SameSite Cookies |
|---|---|---|
| Support | All browsers | Modern browsers |
| Security | Highest | High |
| Use Case | Most reliable protection | Easy default protection |
| Complexity | Medium | Low |
CSRF Token
Support
All browsers
Security
Highest
Use Case
Most reliable protection
Complexity
Medium
SameSite Cookies
Support
Modern browsers
Security
High
Use Case
Easy default protection
Complexity
Low
Common questions
- ›“What is CSRF and how does it work?”
- ›“How do CSRF tokens prevent attacks?”
- ›“Explain SameSite cookie attribute.”
- ›“How do you protect a web app from CSRF?”
What interviewers look for
- Clear attack flow explanation
- Understanding of tokens and SameSite
- Knowledge of protecting all state-changing endpoints
- Defense-in-depth thinking
Short answer (60 sec)
CSRF tricks a logged-in user into performing unwanted actions. Prevent with CSRF tokens (unique per session) and SameSite=Strict cookies. Always protect POST/PUT/DELETE requests.
Detailed answer (senior level)
CSRF exploits automatic cookie sending. The attacker creates a page that submits requests to the target site. Protection methods: 1) CSRF tokens (unique value per session, validated on server), 2) SameSite cookies (prevents cross-site sending), 3) Framework middleware. Protect all state-changing endpoints and never use GET for mutations.
- Only protecting some endpoints
- Using GET requests for state changes
- Storing tokens in localStorage
- Not using SameSite cookies
- Forgetting to validate tokens on every mutation
- ✓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