Authentication & Authorization Medium technical 0 views 1 min read

What is CSRF and how do you prevent it?

Peer-reviewed by HireXTech Technical Panel • Updated for 2025/2026 hiring • Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Authentication & Authorization conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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=Lax or Strict so 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 Origin or Referer header on state-changing requests.
  • Require a non-simple content type such as JSON, which triggers a preflight.
  • Prefer Authorization header 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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?