Part II — The Shield · Lesson 3.15
Cross-Site Request Forgery (CSRF)
In one lineAnother site makes the user's browser send an authenticated request — cookies attach automatically.
Where you've seen itA hidden auto-submitting form on an unrelated page, POSTing to your bank while your session cookie is still valid.
Diagram
How it works
- Cookies are attached by the browser based on destination, not on who initiated the request.
- So any site can cause an authenticated write unless something proves the request came from your UI.
SameSite=Lax(now the browser default) stops cross-sitePOSTs while keeping normal top-level navigation working.- CSRF tokens remain necessary where
SameSite=Noneis required (embedded flows, some SSO) — the double-submit cookie pattern is the common implementation. Authorization: Bearerheaders are not auto-attached, so token-in-header APIs are structurally CSRF-immune — but then you're exposed to XSS token theft instead (see 3.5).
Trade-offs
| Defence | Strength | Cost |
|---|---|---|
SameSite=Lax | Blocks most CSRF | Breaks legitimate cross-site POST flows |
SameSite=Strict | Strongest | User arrives from a link already "logged out" |
| CSRF token | Works with None | Server state or signed double-submit |
| Origin check | Simple, effective | Some proxies strip the header |
Interview angle
"Are you safe from CSRF if your API uses JWT in an Authorization header?"
- Structurally yes, because the browser never attaches that header automatically.
- But storing the JWT where JS can read it hands it to any XSS — you traded one risk for another.
- The balanced answer:
HttpOnly+Secure+SameSite=Laxcookies, plus a CSRF token on state-changing routes.
Recap
- CSRF abuses automatic cookie attachment; it needs the write, not the read.
SameSite=Laxcloses most of it; tokens cover the rest.- Header-based auth avoids CSRF but moves the risk to XSS — pick deliberately.