What is CSRF and how do tokens and SameSite stop it?
Short answer
CSRF tricks a logged-in user's browser into sending a state-changing request to a site where they are authenticated, abusing the fact that cookies are sent automatically. It is stopped with anti-CSRF tokens (a secret per-session value the attacker cannot read or guess) and the SameSite cookie attribute, which stops cookies from riding along on cross-site requests.
Cross-site request forgery (CSRF) exploits a quirk of the web: browsers automatically attach a site's cookies to every request to that site, including requests triggered by a different site. If a user is logged in to their bank and then visits an attacker's page, that page can silently fire a form post to the bank — and the browser dutifully includes the session cookie. The bank sees an authenticated request and processes the transfer. The attacker never reads any response; they just need the action to happen.
Why ambient authority is the root cause
CSRF works because authentication is ambient — proven by a cookie the browser sends on its own, with no proof that the request actually originated from the legitimate application. So defenses must add a signal that this request really came from our app.
Anti-CSRF tokens (synchronizer pattern)
The server embeds a secret, per-session, unpredictable token in its own forms and requires it back on every state-changing request. An attacker's cross-origin page cannot read this token (the Same-Origin Policy blocks reading the response that contains it) and cannot guess it. So the forged request lacks a valid token and is rejected.
SameSite cookies
The SameSite cookie attribute tells the browser when to send the cookie:
- Strict — never on cross-site requests (strongest, but can break inbound links to logged-in pages).
- Lax — sent on top-level navigations (clicking a link) but not on cross-site POSTs/sub-resource requests; a sensible default that blocks classic form-post CSRF.
- None — always sent (requires
Secure); needed for legitimate cross-site contexts.
The interaction with XSS
CSRF tokens assume the attacker is off-site. If the app also has XSS, the injected script runs on-origin and can read the token — so XSS defeats CSRF protection. The two must both be fixed.
Interviewers look for "automatic cookie sending" as the root cause, the token's unguessability tied to the Same-Origin Policy, the Lax-vs-Strict distinction, and the XSS caveat.
Likely follow-ups
- Why does an attacker's CSRF page fail when a synchronizer token is required?
- What is the difference between SameSite=Lax and SameSite=Strict?
- Why does CSRF protection not help if the site also has XSS?