download

CORS blocks other origins. Why does CSRF still hit POST /account/email?

Security~10 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why does restricting CORS fail to stop this cross-site POST?
  2. Fix update_email(headers, form, session) to check Fetch Metadata (Sec-Fetch-Site) and a per-session CSRF token with hmac.compare_digest.
  3. Why is moving the session token into localStorage a poor CSRF fix?
"CODE · PYTHON"
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)
  1. "CORS SIMPLE REQUESTS"

    An HTML <form method="POST"> using application/x-www-form-urlencoded is a CORS simple request. Does the browser send an OPTIONS preflight before firing it?

  2. "LAYERS OF DEFENSE"

    Combine SameSite=Lax (or Strict) cookies, a Sec-Fetch-Site check rejecting cross-site calls, and a per-session token compared with hmac.compare_digest.

  3. "COOKIES VERSUS LOCALSTORAGE"

    An HttpOnly cookie stays invisible to JavaScript. What happens to a token in localStorage if 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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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.

requeststarterfixed update_email
Same-origin + valid token200200 (email -> a@ex)
Sec-Fetch-Site: cross-site200 (CSRF)403 (cross-site blocked)
Sec-Fetch-Site: same-site (sibling subdomain)200 (CSRF)403 (cross-site blocked)
Missing header + wrong token200 (CSRF)403 (invalid csrf token)

Layer three defenses instead of trusting one header:

  • Session cookie flags: Set HttpOnly; Secure; SameSite=Lax (or SameSite=Strict for sensitive apps). SameSite=Lax stops browsers from attaching cookies on cross-site POST forms while keeping top-level link navigation working. Keep GET routes 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 with hmac.compare_digest to prevent timing leaks. Another origin cannot read the user's page to steal this token.
  • Fetch Metadata (Sec-Fetch-Site): Modern browsers set Sec-Fetch-Site as a forbidden header that page JavaScript cannot spoof. Rejecting values outside same-origin and none blocks both cross-site attacks 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-Origin blocks cross-site POST mutations. CORS simple requests fire without preflight and execute on the server before CORS blocks response reading.
  • Relying only on SameSite=Lax while allowing state changes on GET endpoints like /account/delete. Top-level GET navigations still carry Lax cookies.
  • Moving auth tokens into localStorage to avoid CSRF. Any XSS bug can then steal the long-lived token directly, unlike an HttpOnly cookie.
  • Comparing CSRF tokens with == instead of hmac.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 requires Content-Type: application/json and rejects text/plain or form bodies. An attacker can still submit JSON text inside a text/plain <form> if the parser ignores the header. Pair strict content-type checks with SameSite, Sec-Fetch-Site, and a custom header or CSRF token.
  • "Why does the solution reject Sec-Fetch-Site: same-site as well as cross-site?" same-site includes sibling subdomains such as a marketing blog on blog.app.example. If that subdomain is compromised or hosts untrusted content, it can send cross-origin requests to app.example with SameSite cookies 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 →

Original OfferVibe question. OWASP CSRF Prevention Cheat Sheet · MDN CORS Simple Requests · MDN Sec-Fetch-Site · Python hmac.compare_digest.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.