Skip to content

Cookies, CSRF and CORS

One model underlies all three: the browser attaches ambient credentials automatically, then limits which code may read the responses. Cookies control the first part, the same-origin policy and CORS the second, and CSRF is the attack that exploits the gap.

Cookies are key-value pairs the browser stores and sends automatically, scoped by domain and path. Secure keeps them off plain HTTP, HttpOnly hides them from JavaScript, and SameSite stops them being sent cross-site, which is the primary CSRF defence. CSRF is an attacker’s page causing a state-changing request to your site with the victim’s cookies attached. CORS is the server telling the browser which other origins may read its responses; it is not access control, because the request may already have happened.

Set-Cookie: __Host-session=abc123; Path=/; Max-Age=86400; Secure; HttpOnly; SameSite=Lax
Attribute Effect
Domain Which hosts receive it. Omitted = host-only. .example.com sends it to every subdomain — usually a mistake
Path Sent for matching prefixes. Not a security boundary
Expires / Max-Age Neither = session cookie. Max-Age wins
Secure HTTPS only (and blocked on http:// in development)
HttpOnly Invisible to document.cookie; mitigates XSS session theft
SameSite=Strict Never sent cross-site, including link navigation. Safest, most disruptive
SameSite=Lax Sent on top-level GET navigation only. The modern browser default
SameSite=None Sent cross-site; requires Secure
Partitioned (CHIPS) Tied to the top-level site, so an embed cannot track across sites

Cookie prefixes defend against cookie tossing (a subdomain overwriting a parent cookie): __Host- requires Secure, Path=/ and no Domain; __Secure- requires only Secure. Keep authentication cookies off subdomains that host user content.

The attack needs three things: a cookie sent automatically, a state-changing endpoint accepting a simple request, and no check that the request was intended.

<!-- evil.example.com -->
<form action="https://bank.example.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="5000">
</form>
<script>document.forms[0].submit()</script>

Defences, most effective first:

  1. SameSite=Lax or Strict on session cookies — stops the cookie on cross-site POSTs and removes most CSRF. Lax still allows top-level GET navigation, so GET must never mutate.
  2. CSRF tokens — random value bound to the session, in a form field or header. Synchroniser token: server stores it. Double-submit: token is in a cookie and echoed in a header, and the server checks they match — stateless, weaker if an attacker can set cookies on a subdomain.
  3. Origin / Sec-Fetch-Site checks — reject state-changing requests whose origin is not yours. Cheap and effective as a second layer.
  4. Custom header or JSON content type — cannot be sent as a simple cross-origin form post, so it triggers a preflight your CORS policy rejects. This is why JSON-only APIs are mostly CSRF-safe by accident.

CSRF does not apply to tokens in an Authorization header, because the browser does not attach them. It applies the moment the token lives in a cookie.

An origin is scheme + host + port, so https://app.example.com and https://api.example.com differ. Scripts may not read responses from another origin, but they may still send requests, and simple requests are not even preflighted.

The SOP does not stop loading images, CSS, scripts, iframes, or form submissions. It only stops reading the response — which is why CSRF and CORS are separate concerns.

Simple requests (GET, HEAD, POST with text/plain, application/x-www-form-urlencoded or multipart/form-data, safelisted headers only) are sent immediately with an Origin header. The browser blocks the response if the headers do not allow it — the server has already processed the request. That is the fact people miss.

Everything else is preflighted:

OPTIONS /api/orders/42 HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PATCH
Access-Control-Request-Headers: content-type, authorization
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
Vary: Origin

Only if the preflight passes does the real request go out.

Cookies and HTTP auth cross-origin need both sides to opt in:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Expose-Headers: X-Request-Id, RateLimit-Remaining

Allow-Origin: * is forbidden with credentials; you must echo a specific origin, which means validating Origin against an allow-list — never echoing it blindly. Expose-Headers is required for the script to read anything beyond the safelisted response headers, which explains the classic “the header is in DevTools but response.headers.get() returns null”.

  • Reflecting any Origin back with credentials — any site can read authenticated responses.
  • Allowing null origin, which sandboxed iframes and file:// produce.
  • Wildcard methods/headers plus credentials.
  • Forgetting Vary: Origin on a CDN, so a cached Allow-Origin for site A is served to site B.

CORS is enforced by the browser. curl, a server-side script or an attacker’s client ignores it. If an endpoint must be protected, protect it with authentication and authorisation.

Set-Cookie: __Host-session=<random>; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-Token
Vary: Origin

For a same-site SPA the simplest correct setup is no CORS at all: serve the API from the same origin, session in an HttpOnly; Secure; SameSite=Lax cookie, CSRF token on state-changing requests.

  1. Why does SameSite=None require Secure?
  2. A cookie works in a top-level tab but not in an iframe. What changed?
  3. Why is Allow-Origin: * incompatible with credentials?
  4. How does double-submit CSRF protection fail against a subdomain takeover?
  5. Why can a POST with Content-Type: text/plain reach your server without a preflight?
  • “CORS protects the API.” It restricts browser scripts only; it does nothing for curl.
  • “The preflight failed, so the request was never sent.” For simple requests there is no preflight; only the response is blocked.
  • “HttpOnly prevents XSS.” It prevents reading that cookie. Scripts can still act as the user and read the DOM.
  • “SameSite=Strict everywhere is safest.” It breaks inbound links: a visitor appears logged out until they navigate again.
  • “Path=/admin protects the admin cookie.” Path is not an authorisation boundary.
  • “Logout clears the cookie.” Only if the server sends an expired Set-Cookie; always invalidate server-side too.