CSRF: requests your users never meant to send
Browsers attach cookies to every request to your site, even when another site triggered it. Cross-site request forgery abuses that to act as a logged-in user. Why SameSite cookies changed the game, and when you still need tokens.
In one sentence
Cookies prove which browser sent a request, not which site asked for it. SameSite cookies and CSRF tokens tell your server the request really came from your own pages.
The idea
You're logged in to your bank in one tab. In another tab you open a page with a hidden form that posts to bank.test/transfer. The browser sends that request with your bank cookie, and the bank sees a perfectly authenticated transfer.
Defenses
| Defense | How it helps | Notes |
|---|---|---|
| SameSite=Lax cookies | Cookie isn't sent on cross-site POSTs, iframes or fetches | Default in modern browsers if you don't set it, but set it explicitly |
| SameSite=Strict | Cookie never sent cross-site, even on link clicks | Users arriving from email links look logged out |
| CSRF token | Random value in the form that a foreign site can't read | Needed if you use SameSite=None or old browsers matter |
| Check Origin / Sec-Fetch-Site | Reject state-changing requests from other origins | Cheap extra layer for APIs |
| No state changes on GET | Links and images can't trigger actions | GET /delete?id=4 is CSRF waiting to happen |
Key takeaways
- 01Browsers attach cookies to cross-site requests unless SameSite says otherwise.
- 02Set session cookies to SameSite=Lax (or Strict) explicitly.
- 03Use CSRF tokens or Origin checks for anything that changes state.
- 04Never change state on GET requests.
Check your understanding
1 of 3
Why does CSRF work?
Related concepts
Sessions & cookies
A session cookie is as good as a password while it's valid. Ship it as HttpOnly; Secure; SameSite=Lax, keep it short-lived, and rotate it on login and privilege changes.
7 min read →XSS
XSS is injection into HTML instead of SQL. Escape output by default, never inject raw HTML, and add a Content Security Policy as the safety net.
8 min read →AuthN vs AuthZ
Authentication answers *who are you?* Authorization answers *are you allowed to do this, to this thing, right now?* Most breaches of web apps are the second one missing.
6 min read →