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.
The 60-second answer
Section titled “The 60-second answer”Cookies are key-value pairs the browser stores and sends automatically, scoped by domain and path.
Securekeeps them off plain HTTP,HttpOnlyhides them from JavaScript, andSameSitestops 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.
Cookie attributes
Section titled “Cookie attributes”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:
SameSite=LaxorStricton session cookies — stops the cookie on cross-site POSTs and removes most CSRF.Laxstill allows top-level GET navigation, soGETmust never mutate.- 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.
Origin/Sec-Fetch-Sitechecks — reject state-changing requests whose origin is not yours. Cheap and effective as a second layer.- 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.
Same-origin policy
Section titled “Same-origin policy”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.1Origin: https://app.example.comAccess-Control-Request-Method: PATCHAccess-Control-Request-Headers: content-type, authorizationHTTP/1.1 204 No ContentAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Allow-Methods: GET, POST, PATCH, DELETEAccess-Control-Allow-Headers: Content-Type, AuthorizationAccess-Control-Max-Age: 600Vary: OriginOnly if the preflight passes does the real request go out.
Credentials
Section titled “Credentials”Cookies and HTTP auth cross-origin need both sides to opt in:
Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Expose-Headers: X-Request-Id, RateLimit-RemainingAllow-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”.
Misconfigurations that get exploited
Section titled “Misconfigurations that get exploited”- Reflecting any
Originback with credentials — any site can read authenticated responses. - Allowing
nullorigin, which sandboxed iframes andfile://produce. - Wildcard methods/headers plus credentials.
- Forgetting
Vary: Originon a CDN, so a cachedAllow-Originfor 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.
A sane baseline
Section titled “A sane baseline”Set-Cookie: __Host-session=<random>; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=LaxAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Allow-Credentials: trueAccess-Control-Allow-Methods: GET, POST, PATCH, DELETEAccess-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-TokenVary: OriginFor 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.
Follow-up questions
Section titled “Follow-up questions”- Why does
SameSite=NonerequireSecure? - A cookie works in a top-level tab but not in an iframe. What changed?
- Why is
Allow-Origin: *incompatible with credentials? - How does double-submit CSRF protection fail against a subdomain takeover?
- Why can a
POSTwithContent-Type: text/plainreach your server without a preflight?
Common traps
Section titled “Common traps”- “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.
- “
HttpOnlyprevents XSS.” It prevents reading that cookie. Scripts can still act as the user and read the DOM. - “
SameSite=Stricteverywhere is safest.” It breaks inbound links: a visitor appears logged out until they navigate again. - “
Path=/adminprotects 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.