CSRF Protection Interview Questions

4 questions developers actually get asked about csrf protection — with clear, practical answers you can use to prepare.

Q1. What is a CSRF attack and why does it work?

CSRF (Cross-Site Request Forgery) is an attack where a page you did not write tricks a logged-in user's browser into sending a state-changing request to a site they are authenticated on. It works because browsers automatically attach cookies (including session cookies) to any request bound for the cookie's domain, even when the request is triggered from another origin. The server sees a valid session and executes the action, unaware the user never intended it.

Q2. How does a CSRF token prevent the attack?

The server issues a random, unguessable token tied to the user's session and includes it in every form it renders. On submit, the server checks that the submitted token matches the one it stored. An attacker's page cannot read that token because the browser's same-origin policy blocks cross-site reads of the victim site's HTML, so any forged request arrives with the token missing or wrong and gets rejected. The session cookie rides along just like before, but the cookie alone is no longer enough.

Q3. What is the difference between CSRF and XSS?

XSS (Cross-Site Scripting) is code injected INTO your site that runs in the context of your own origin, so it can read anything your page can read, including CSRF tokens. CSRF is the opposite: an attacker's OWN page tries to trigger actions on your site without being able to read anything from your origin. XSS defeats CSRF protection (it can read the token), so input validation and output escaping are upstream of any CSRF story. They are different attacks with different defenses and both matter.

Q4. When is SameSite=Strict on a session cookie enough to skip CSRF tokens?

SameSite=Strict tells the browser to withhold the cookie on any cross-site request, which kills most CSRF vectors. But it is not a full replacement: older browsers may not honor it, subdomain setups can widen "same site" wider than you expect, and some legitimate flows (like following a link from an email into a logged-in page) break under Strict. Best practice is defense in depth: set SameSite=Lax or Strict AND keep CSRF tokens on. If one fails, the other still holds.

Want the full concept, analogies, and AI prompts for csrf protection?

Read the full CSRF Protection block →