What is CSRF and how do you prevent it?
Assesses fundamental understanding of Authentication & Authorization conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Cross-Site Request Forgery tricks a logged-in user's browser into sending an authenticated request to your site. Because browsers attach cookies automatically, a malicious page can trigger a state-changing request without the user's intent.
<img src="https://bank.example/transfer?to=attacker&amount=1000">
Preventions:
- Set cookies
SameSite=LaxorStrictso they are not sent on cross-site requests. - Use anti-CSRF tokens: a random value stored in the session and required in the request body or a custom header, validated server-side.
- Check the
OriginorRefererheader on state-changing requests. - Require a non-simple content type such as JSON, which triggers a preflight.
- Prefer
Authorizationheader tokens over cookies for APIs, since headers are not attached automatically.
Note that XSS defeats most CSRF defences, so prevent XSS too. Combine SameSite cookies with tokens for defence in depth.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.