CORS blocks other origins. Why does CSRF still hit POST /account/email?
Question
A cookie-authenticated endpoint POST /account/email parses application/x-www-form-urlencoded fields ([email protected]). The server restricts Access-Control-Allow-Origin to https://app.example and checks session["user_id"]. Yet a hidden <form> on https://evil.example still changes a signed-in user's email without triggering a CORS preflight.
- Why does restricting CORS fail to stop this cross-site
POST? - Fix
update_email(headers, form, session)to check Fetch Metadata (Sec-Fetch-Site) and a per-session CSRF token withhmac.compare_digest. - Why is moving the session token into
localStoragea poor CSRF fix?
def update_email(headers, form, session): # Cookie auth already loaded session; CORS allows only app.example. if not session or not session.get("user_id"): return 401, "login required" return 200, f"email -> {form.get('email', '')}"
Show hints (3)
- "CORS SIMPLE REQUESTS"
An HTML
<form method="POST">usingapplication/x-www-form-urlencodedis a CORS simple request. Does the browser send anOPTIONSpreflight before firing it? - "LAYERS OF DEFENSE"
Combine
SameSite=Lax(orStrict) cookies, aSec-Fetch-Sitecheck rejecting cross-site calls, and a per-session token compared withhmac.compare_digest. - "COOKIES VERSUS LOCALSTORAGE"
An
HttpOnlycookie stays invisible to JavaScript. What happens to a token inlocalStorageif the app ever has one XSS bug?
Show checked explanation
An HTML <form> POST with application/x-www-form-urlencoded is a CORS simple request, so the browser sends the session cookie with no preflight. CORS only blocks the attacker from reading the response after the email has already changed. Defend with SameSite=Lax (or Strict) cookies, a Sec-Fetch-Site check, and a per-session synchronizer token compared via hmac.compare_digest.
import hmac def update_email(headers, form, session): if not session or not session.get("user_id"): return 401, "login required" if headers.get("Sec-Fetch-Site", "") not in ("", "same-origin", "none"): return 403, "cross-site blocked" sent, want = form.get("csrf_token", ""), session.get("csrf_token", "") if not want or not hmac.compare_digest(sent, want): return 403, "invalid csrf token" return 200, f"email -> {form.get('email', '')}" sess = {"user_id": "u1", "csrf_token": "tok_9f"} cases = [("ok", "same-origin", "tok_9f"), ("xsite", "cross-site", "tok_9f"), ("bad_tok", "", "wrong")] for tag, site, tok in cases: hdr, frm = {"Sec-Fetch-Site": site}, {"email": "a@ex", "csrf_token": tok} print(tag, "->", update_email(hdr, frm, sess))
ok -> (200, 'email -> a@ex') xsite -> (403, 'cross-site blocked') bad_tok -> (403, 'invalid csrf token')
Author-checked on CPython 3.12.10 against synthetic same-origin, cross-site, same-site, missing-header, and invalid-token HTTP fixtures; official OWASP, MDN, and Python hmac links checked. Checked by an editor other than the author.
Walkthrough
CORS controls which cross-origin pages may read a response, not whether the browser sends a simple request. A <form method="POST"> with application/x-www-form-urlencoded, multipart/form-data, or text/plain is a CORS simple request. The browser sends zero OPTIONS preflight and attaches the user's session cookie automatically. evil.example never sees the 200 body, yet the server already updated the email.
| request | starter | fixed update_email |
|---|---|---|
| Same-origin + valid token | 200 | 200 (email -> a@ex) |
Sec-Fetch-Site: cross-site | 200 (CSRF) | 403 (cross-site blocked) |
Sec-Fetch-Site: same-site (sibling subdomain) | 200 (CSRF) | 403 (cross-site blocked) |
| Missing header + wrong token | 200 (CSRF) | 403 (invalid csrf token) |
Layer three defenses instead of trusting one header:
- Session cookie flags: Set
HttpOnly; Secure; SameSite=Lax(orSameSite=Strictfor sensitive apps).SameSite=Laxstops browsers from attaching cookies on cross-sitePOSTforms while keeping top-level link navigation working. KeepGETroutes free of state changes. - Synchronizer CSRF token: Generate a random per-session token with
secrets.token_urlsafe(32), embed it in forms or a custom header, and check it withhmac.compare_digestto prevent timing leaks. Another origin cannot read the user's page to steal this token. - Fetch Metadata (
Sec-Fetch-Site): Modern browsers setSec-Fetch-Siteas a forbidden header that page JavaScript cannot spoof. Rejecting values outsidesame-originandnoneblocks bothcross-siteattacks and compromised sibling subdomains (same-site). When the header is absent on older clients, the synchronizer token still blocks the request.
Why localStorage is a bad trade. Moving the session token from cookies to localStorage stops automatic browser attachment, which hides CSRF. In exchange, any single XSS flaw on app.example can run localStorage.getItem(...) and exfiltrate the token permanently. Keeping sessions in HttpOnly cookies plus CSRF tokens protects against both threats.
Common mistakes
- Assuming
Access-Control-Allow-Originblocks cross-sitePOSTmutations. CORS simple requests fire without preflight and execute on the server before CORS blocks response reading. - Relying only on
SameSite=Laxwhile allowing state changes onGETendpoints like/account/delete. Top-levelGETnavigations still carryLaxcookies. - Moving auth tokens into
localStorageto avoid CSRF. Any XSS bug can then steal the long-lived token directly, unlike anHttpOnlycookie. - Comparing CSRF tokens with
==instead ofhmac.compare_digest, or reusing one static token across all users instead of binding it to the session.
Follow-up questions
- "If the endpoint accepts only
Content-Type: application/json, does that stop HTML form CSRF?" Only if the server strictly requiresContent-Type: application/jsonand rejectstext/plainor form bodies. An attacker can still submit JSON text inside atext/plain<form>if the parser ignores the header. Pair strict content-type checks withSameSite,Sec-Fetch-Site, and a custom header or CSRF token. - "Why does the solution reject
Sec-Fetch-Site: same-siteas well ascross-site?"same-siteincludes sibling subdomains such as a marketing blog onblog.app.example. If that subdomain is compromised or hosts untrusted content, it can send cross-origin requests toapp.examplewithSameSitecookies attached. - "When is a double-submit cookie pattern weaker than a server-side synchronizer token?" A stateless double-submit cookie can be beaten if an attacker controls a sibling subdomain and overwrites the CSRF cookie via
Domain=.app.example. Bind the token with an HMAC tied to the user's session ID or store it server-side.
What a strong answer covers
Explains why CORS simple requests bypass preflight and execute state changes. Layers SameSite=Lax/Strict cookies, Sec-Fetch-Site checks, and per-session hmac.compare_digest CSRF tokens, and explains why localStorage trades CSRF for XSS token theft.
Open in interactive practice deck →