Lesson 8 of 20 · 16m
CSRF: the requests your users' browsers make for someone else
Why CORS doesn't save cookie auth, what SameSite=Lax actually blocks, and the token and header checks that do.
Here is the mechanism: browsers attach your site's cookies to every request aimed at your origin — including requests triggered by a page on evil.example. An auto-submitting form there does this:
<form action="https://app.example.com/api/email" method="POST">
<input name="email" value="attacker@evil.example">
</form><script>document.forms[0].submit()</script>The victim's browser sends their session cookie along. Your server sees an authenticated POST and changes the email. Nobody's credentials were stolen; the browser did exactly what it was built to do. That's cross-site request forgery.
The wrong mental model is "CORS protects me." CORS gates reading responses across origins, and it only applies to requests JavaScript sends with fetch. A plain form POST is a "simple request": no preflight, no CORS check. The request fires either way.
This used to be everywhere — drive-by pages rewrote home routers' DNS through their admin panels, and CSRF sat on the OWASP Top 10 for years. It dropped off the 2021 list largely because SameSite=Lax became Chrome's default in early 2020 and other browsers followed. But Lax only withholds cookies on cross-site POSTs — top-level GET navigations still carry them, which makes the first rule below load-bearing. And "site" means eTLD+1: a sibling subdomain like api.example.com is same-site with app.example.com, so Lax won't save you from a subdomain you don't control.
The defenses, in order
- No state changes on GET.
GET /api/disable-2falooks harmless and is fully CSRF-able under Lax, because clicking a link is a top-level navigation. Mutations take POST/PUT/DELETE — plus one of the checks below. - Synchronizer token. A per-session random value rendered into forms and verified server-side:
<input type="hidden" name="csrf" value="hJ9k…">Attacker pages can't read your token, so they can't forge a valid form. Frameworks ship this — Django {% csrf_token %}, Rails csrf_meta_tags, Laravel @csrf — and it only works if nothing exempts it (except, skip_before_action :verify_authenticity_token).
3. Fetch-metadata / Origin check. Sec-Fetch-Site: cross-site on a state-changing request is a reject; Sec-Fetch-Mode, Sec-Fetch-Dest and Sec-Fetch-User tell you how the request was triggered. A present-but-wrong Origin is a reject. Cheap, and it catches the cases tokens miss.
4. Custom header contract. JSON APIs can require something no HTML form can send — X-CSRF-Token, Authorization: Bearer, even a plain X-Requested-With. A cookie-authed API that demands one is structurally unforgeable by a form — but only if the route actually rejects requests without it; an optional header is no header.
5. SameSite=Strict where breaking inbound links is acceptable — admin panels. Lax stays the floor.
Request shape is the quiet detail. Only application/x-www-form-urlencoded, multipart/form-data and text/plain go preflight-free — a JSON API that parses the body by shape rather than by declared Content-Type accepts a forged text/plain body, which is why "require application/json at the route" is itself a control. And Sec-Fetch-* and Origin are forbidden headers: attacker JavaScript can't set them at all, so the browser's answer can be trusted for rejection.
A weaker-but-simple pattern is the double-submit cookie: a random value in a cookie, mirrored into a form field, compared server-side. It stops the classic form attack without session state, but a subdomain XSS can overwrite the cookie — prefer the synchronizer token where you can.
Two edges worth knowing. Login CSRF is real: an attacker logs the victim in as the attacker, and everything the victim types lands in the wrong account — protect the login form with a token too. OAuth flows carry their own version — the state parameter is CSRF protection for the authorization response, not a session decoration. And Authorization: Bearer tokens dodge this entire class because nothing attaches them automatically; the tradeoff is that JavaScript must store them, which is the XSS-and-JWT lesson's problem.
Practice
Mutations on POST-or-better only. Synchronizer tokens or a required custom header on cookie-authed routes, Sec-Fetch-Site/Origin rejection underneath, Lax minimum on session cookies. Then test it: submit the form from a different origin and watch it fail.
Keep reading
Related articles from the SudoSecurity blog.
Building a Production REST API With Node.js and Express
Build a REST API in Node.js and Express the way production systems need: input validation, JWT auth, refresh token rotation, status codes, rate limiting, idempotency keys, and centralized error handling.
RSA in JavaScript Part 2: The JWT Is Where You'll Actually Meet It
Most JavaScript developers never call an RSA function directly. They verify an RS256 token, and two classic attacks turn that into an authentication bypass — both demonstrated here, both fixed by one line.
RSA Signatures: The Version in Most Tutorials Is Forgeable
Signing is encryption with the keys swapped, and that symmetry is exactly what makes the naive implementation breakable. Here are two forgeries executed against textbook RSA signatures, and what PSS does that hashing alone cannot.
Ask Java for AES and You Get ECB. Nobody Warns You.
Cipher.getInstance("AES") compiles, runs, encrypts, decrypts, and hands you the weakest mode in the box. Here is the OpenJDK source that makes that decision, and the line where ECB gets chosen for you.