What you'll learn: By the end of this lesson you will be able to explain why a browser sends your session cookie on a request another site caused, compare the main CSRF defenses (
SameSitecookies, synchronizer and double-submit tokens,OriginandRefererchecks, Fetch Metadata), say which attacks each stops and which it misses, explain why CORS is not a CSRF defense, and decide who may frame your page withframe-ancestorsandX-Frame-Options. A TypeScript lab runs ten requests against eleven defenses.
A hotel key card opens your door for whoever holds it, and the lock does not ask who is holding it. Imagine a stranger who cannot steal your card but can steer your hand: "press that button". That is cross-site request forgery (CSRF): the browser holds your key card (your cookies), attaches it to every request to the site that issued it, and does not check which page asked. Clickjacking is a cousin: a transparent sheet over a form, so you think you press "play" while your finger lands on "confirm".
The running example is a shop at https://shop.example with POST /transfer, which sends store credit to another account. Attackers run https://evil.example. Three illustrations run through the lesson: a minimal example (a hidden form on the attacker's page), a realistic example (the shop with layered defenses) and a failure example (a sibling subdomain that same-site rules still trust). It builds on Cross-Site Scripting (XSS) and Its Defenses and the Same-Origin Policy and CORS.
The core idea
- CSRF exists because cookies are attached automatically. MDN: the attacker tricks the user or browser into making a request to the target site from a malicious site, the request includes the user's credentials, and the server acts as if the user intended it.
- Each defense answers one question: did the request come from my page (a token), where did it come from (
Origin,Referer, Fetch Metadata), should the cookie be attached at all (SameSite)? None is complete alone, so layer them. - Clickjacking is a framing problem. The request is real, so tokens and origin checks pass. Control who may frame the page.
How a forged request works
MDN says an attack is possible when a site changes state with HTTP requests, validates the user only by cookies, and uses only parameters an attacker can predict. The attacker's page holds a hidden form aimed at /transfer and submits it on load. The browser sends it and, because the cookie belongs to shop.example, attaches it.
Figure 1. A forged request carries the real cookie
How to read this: the attacker never sees the cookie or a response. The browser sends, and the cookie arrives because it matches the destination.
Figure 2. The same request in time order
How to read this: the whole attack is the middle arrow. Every defense below removes the cookie from it or fails a check at the server.
Two rules come first. Never change state on a safe method: MDN's checklist and OWASP both say so, because a GET needs no form (an image is enough) and most defenses skip safe methods. And XSS defeats every defense here, says OWASP, because script on your origin can read the token. Fix XSS first.
SameSite cookies: do not send the cookie
MDN gives three values. Strict sends the cookie only for requests from the same site that set it. Lax also sends it cross-site for a top-level navigation (the address bar URL changes: a link, a form submission) that uses a safe method, which excludes fetch(), images, frames, POST, PUT and DELETE. None sends it always and requires Secure. Some browsers default to Lax when the attribute is absent, in a more permissive form that also sends the cookie on POST requests within two minutes of it being set. "Same site" includes the scheme.
Figure 3. Is the cookie sent?
by the user?"} -->|"yes"| Y["Cookie sent"] Q -->|"no, cross-site"| V{"Cookie's
SameSite value"} V -->|"None"| Y V -->|"Strict"| N["Cookie not sent"] V -->|"Lax"| L{"Top-level navigation
and safe method?"} L -->|"yes"| Y L -->|"no"| N
How to read this: the lab's first table runs this chart for six cookie settings and seven situations. A cross-site form POST, image or fetch() gets no Lax cookie, but a link click does.
It is cheap and strong, but MDN calls it not a complete defense: an attacker can trigger a top-level navigation, and it works on the site, not the origin, so you must trust every subdomain. OWASP says to treat it as defense in depth. In the lab, a form posted from a sibling subdomain (scenario H) gets the cookie under both Lax and Strict.
Tokens: prove the request came from your page
A synchronizer token is a random value the server stores with the session and puts in each page. State-changing requests send it back, preferably in a header (OWASP: more secure than a hidden field), and the server compares it with the stored one. OWASP says tokens should be unique per session, secret and unpredictable. An attacker's page cannot read yours, so it cannot learn the token.
Figure 4. The synchronizer token
How to read this: the cookie proves who the user is, the token proves which page sent the request. The attacker gets the first for free and cannot get the second.
To avoid per-session server state there is the double-submit cookie: the token is also a cookie and the server checks the two match. OWASP's naive version is "for reference only" and open to cookie injection: an attacker who controls a subdomain can plant a cookie with a value they know and submit the same value. The signed version binds the token to the session with an HMAC, so a token the attacker legitimately got for their own session fails for the victim (the lab's scenario I). A custom header alone also works for AJAX endpoints, since a cross-origin request with one needs a preflight.
Where did it come from: Origin, Referer and Fetch Metadata
Some headers cannot be set by script. Origin is added to cross-origin requests and to same-origin POST, PUT, PATCH, DELETE and OPTIONS (MDN), and is null for an opaque origin such as a sandboxed frame. OWASP: verify it against trusted origins, fall back to Referer, reject when neither is trusted, and never allow-list null.
Fetch Metadata adds Sec-Fetch-Site: same-origin, same-site, cross-site or none (user-initiated), a forbidden header name per MDN. OWASP calls it the primary signal and says falling back to origin verification is mandatory. The web.dev policy: allow when the header is missing (older browsers get no protection), allow same-origin, same-site and none, allow a top-level GET navigation whose destination is not object or embed, reject the rest, typically with 403. Two choices matter: allowing same-site lets a sibling subdomain through (scenario H), and allowing top-level GET navigations means a state-changing GET is still forged (scenario C).
CORS is not a CSRF defense
CORS relaxes the same-origin policy for reading responses; it does not stop a request being sent. MDN says a site is exposed to an origin if its response to a state-changing request carries Access-Control-Allow-Origin for that origin together with Access-Control-Allow-Credentials. A JSON API is protected in practice because application/json or a custom header needs a preflight that the server does not approve (scenario E, never sent). A simple content type such as text/plain is sent without one (scenario F), so check a token, header or origin as well. See CORS in Practice.
Clickjacking: who may frame this page?
Two headers say who may embed a page, and both must be HTTP headers: a meta element has no effect. Content-Security-Policy: frame-ancestors takes 'none', 'self' or a list of origins; it checks every ancestor and does not fall back to default-src (MDN), so default-src 'none' still lets anyone embed the page. X-Frame-Options is older: DENY blocks all framing, SAMEORIGIN allows it only if all ancestors share the page's origin, and ALLOW-FROM is obsolete and ignored by modern browsers. When both are sent, OWASP quotes the CSP specification: X-Frame-Options must be ignored. OWASP recommends 'none' unless framing is needed.
Figure 5. May this page be framed?
in a frame?"} -->|"no"| L["Loads"] S -->|"yes"| M{"Policy sent as an
HTTP header?"} M -->|"no, meta element"| A["Anyone may frame it"] M -->|"yes"| F{"frame-ancestors
present?"} F -->|"yes"| C["Every ancestor must match
(X-Frame-Options ignored)"] F -->|"no"| X{"X-Frame-Options"} X -->|"DENY"| B["Blocked"] X -->|"SAMEORIGIN"| SO["Allowed only if every
ancestor is same-origin"] X -->|"other or none"| A
How to read this: it is the lab's mayFrame function, run on ten header combinations and five embedding situations, including a trusted page nested inside an attacker's.
OWASP adds three points. Frame-busting JavaScript is supplementary and less reliable, with published bypasses. SameSite keeps cookies out of cross-site framed requests but does not stop framing. DoubleClickjacking targets a top-level window, so framing headers do not stop it; for sensitive actions OWASP recommends server-side transaction authorization.
Choosing
| Defense | Stops | Misses |
|---|---|---|
SameSite=Lax or Strict |
Cross-site forms, images, fetch() |
Same-site attackers; link GETs (Lax) |
| Synchronizer or signed token | Any request without the token | XSS |
Origin and Referer check |
Other origins | Missing headers, if allowed |
| Fetch Metadata | Cross-site requests at the edge | Old browsers; same-site if allowed |
frame-ancestors |
Clickjacking | Forged requests |
Build it: ten requests, eleven defenses
Goal. Predict, then see, which of ten requests (one real user, nine forgeries) each of eleven defenses lets through, and which header combinations let a page be framed.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm) and models the browser's cookie and header rules and the server's checks on a virtual network. Nothing is sent.
cd examples/frontend
pnpm install
cd labs/csrf-defenses-model
pnpm test # 53 tests
node src/demo.ts
Steps.
- In section 1, the
Laxrow is sent for a link click and not for a form POST, image orfetch(). - In section 2, row C (a link to a state-changing
GET) staysFORGEDeven underlayered: no check runs on a safe method. Row E is.everywhere because it is never sent. - Rows H and I are the same-site attacks: compare
fmwithfm-samefor H, andnaivewithsignedfor I. Section 3 prints the reason for the cells that teach something.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, the lab's demo, node src/demo.ts):
CSRF and clickjacking defences: who gets the cookie, who passes the check, who may frame
=== 1. SameSite: is the cookie sent? (target https://shop.example, cookie Secure)
cookie same-site POST typed URL link, GET form, POST iframe, GET img, GET fetch, POST
Strict sent sent - - - - -
Lax sent sent sent - - - -
None; Secure sent sent sent sent sent sent sent
None (no Secure) - - - - - - -
unset, default Lax sent sent sent - - - -
unset, default None sent sent sent sent sent sent sent
=== 2. Ten requests against eleven defences (the victim is logged in to shop.example)
Each column turns on one defence; the session cookie is SameSite=None except where the column says otherwise.
A REAL USER user's own form, with the token
B forgery other site auto-submits a form (POST)
C forgery other site links to a state-changing GET
D forgery other site embeds it as an image (GET)
E forgery other site: fetch, JSON body, credentials
F forgery other site: fetch, text/plain body (simple)
G forgery sandboxed frame on other site submits a form
H forgery sibling subdomain submits a form
I forgery sibling subdomain plants a csrf cookie, then submits
J forgery other site, browser without Fetch Metadata
none lax strict origin fm fm-same sync naive signed header layered
A ok ok ok ok ok ok ok ok ok ok ok
B FORGED . . . . . . . . . .
C FORGED FORGED . FORGED FORGED FORGED FORGED FORGED FORGED FORGED FORGED
D FORGED . . FORGED . . FORGED FORGED FORGED FORGED .
E . . . . . . . . . . .
F FORGED . . . . . . . . . .
G FORGED . . . . . . . . . .
H FORGED FORGED FORGED . FORGED . . . . . .
I FORGED FORGED FORGED . FORGED . . FORGED . . .
J FORGED . . . FORGED FORGED . . . . .
ok: the real user's request went through. FORGED: the server carried out the forgery. .: stopped (the reason is in section 3).
=== 3. Why, for the cells that teach something
B x lax stopped at "no session cookie": the browser did not attach the session cookie, so the server sees a logged-out request
C x lax FORGED at "executed": no server-side check
C x layered FORGED at "executed": safe method, not checked
D x lax stopped at "no session cookie": the browser did not attach the session cookie, so the server sees a logged-out request
E x none stopped at "not sent": cross-origin preflight; the server grants no CORS access
F x header stopped at "rejected by the server": x-csrf-protect missing
G x origin stopped at "rejected by the server": Origin is null (opaque origin)
H x lax FORGED at "executed": no server-side check
H x fm FORGED at "executed": Sec-Fetch-Site: same-site (allowed by this policy)
H x fm-same stopped at "rejected by the server": Sec-Fetch-Site: same-site
I x naive FORGED at "executed": token equals the csrf cookie
I x signed stopped at "rejected by the server": MAC is not valid for this session
J x fm FORGED at "executed": no Sec-Fetch-Site header (older browser): allowed
=== 4. Origin and Referer verification (trusted: https://shop.example)
Origin is the shop allow Origin https://shop.example is trusted
Origin is another site reject Origin https://evil.example is not trusted
Origin is a lookalike host reject Origin https://shop.example.evil.example is not trusted
Origin is the shop over http reject Origin http://shop.example is not trusted
Origin is null reject Origin is null (opaque origin)
no Origin, Referer is the shop allow no Origin; Referer origin https://shop.example is trusted
no Origin, Referer is a lookalike reject no Origin; Referer origin https://shop.example.evil.example is not trusted
neither header reject neither Origin nor Referer
=== 5. Fetch Metadata resource isolation policy
Sec-Fetch-Site mode dest method same-site allowed same-origin only
same-origin cors empty POST allow allow
none navigate document GET allow allow
same-site navigate document POST allow reject
cross-site navigate document GET allow allow
cross-site navigate document POST reject reject
cross-site navigate embed GET reject reject
cross-site no-cors image GET reject reject
cross-site cors empty POST reject reject
(missing) POST allow allow
=== 6. Clickjacking: may this page be framed? (page https://shop.example/checkout)
policy top-level own page partner evil own page in evil
no header loads loads loads loads loads
X-Frame-Options: DENY loads BLOCKED BLOCKED BLOCKED BLOCKED
X-Frame-Options: SAMEORIGIN loads loads BLOCKED BLOCKED BLOCKED
X-Frame-Options: ALLOW-FROM partner loads loads loads loads loads
frame-ancestors 'none' loads BLOCKED BLOCKED BLOCKED BLOCKED
frame-ancestors 'self' loads loads BLOCKED BLOCKED BLOCKED
frame-ancestors 'self' partner loads loads loads BLOCKED BLOCKED
frame-ancestors 'none' + XFO SAMEORIGIN loads BLOCKED BLOCKED BLOCKED BLOCKED
default-src 'none' only loads loads loads loads loads
XFO DENY in a meta element loads loads loads loads loads
never Content-Security-Policy: frame-ancestors 'none'
X-Frame-Options: DENY
both headers say the same thing
same-origin Content-Security-Policy: frame-ancestors 'self'
X-Frame-Options: SAMEORIGIN
both headers say the same thing
allow Content-Security-Policy: frame-ancestors 'self' https://partner.example
X-Frame-Options: (none can express this)
X-Frame-Options cannot name another origin (ALLOW-FROM is obsolete), so a browser without frame-ancestors gets no protection
What the lab does not show. No browser and no network. The cookie rules follow MDN and ignore details such as the two-minute window for defaulted Lax. Frame-ancestors matching is simplified, and the signed token is a plain HMAC with a made-up secret. The matrix shows what the model predicts, not what every browser version does.
Break it. In a scratch copy of src/defenses.ts, make checkSignedDoubleSubmit return the naive result without checking the HMAC. Scenario I then succeeds under signed and its test fails. Throw the copy away.
Stretch. Add the two-minute defaulted-Lax window to the cookie model.
In practice: sending store credit from a shop
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The shop's front end calls POST /transfer. The session cookie has no SameSite attribute and there is no token. The company also runs blog.shop.example, where members post comments with limited HTML, owned by another team. Five engineers own the shop.
Starting architecture
Figure 6. Cookie only, and a neighbour in the same site
How to read this: nothing at the shop asks where a request came from or whether the page meant to send it.
Options considered
| Option | What it fixes | Risk |
|---|---|---|
SameSite=Lax only |
Cross-site forms, images, fetch() |
The blog is still trusted |
| Add a synchronizer token | Requests without the page's token | XSS on the shop defeats it |
Fetch Metadata (same-origin only) with an Origin fallback |
Other sites and the blog | Old browsers rely on the fallback |
The decision
| Field | Decision record |
|---|---|
| Context | Cookie-only authentication, a same-site neighbour that accepts user HTML, and a transfer action. |
| Decision | SameSite=Lax, a synchronizer token in a header for non-safe methods, a Fetch Metadata policy allowing only same-origin and none (plus top-level GETs) with an Origin fallback, no state change on GET, and frame-ancestors 'none' on pages with actions. |
| Consequences, good | Several independent checks must fail together; the blog can no longer act as the user. |
| Consequences, bad | Every API client must send the token; a framing partner needs a specific list. |
| Revisit when | A partner must frame a page. |
Rollout and verification
- Log before blocking: run the token, Fetch Metadata and
Originchecks in report-only mode and count what they would reject. - Ship the token to the front end first, then enforce it.
- Test real flows: a link from an email into the shop is a top-level
GETand must still work withLax.
The 2 a.m. failure
Support reports store credit leaving the accounts of members who read one post on the blog. A comment there holds a form that submits itself to /transfer when the post opens. The shop had SameSite=Lax and a policy that allows same-site, and the blog is the same site, so both let it in. The token check was still in report-only mode.
First three checks: (1) read the report-only log of the token check, which shows forged requests with no token and the blog's origin; (2) confirm the cookie was attached; (3) find where else user HTML is hosted under the shop's site. Mitigation: switch the token check to enforcing and allow only same-origin in Fetch Metadata. Follow-up: treat every subdomain that accepts user content as an attacker, sanitize the blog's HTML as in the XSS lesson, and add the lab's row H to the tests.
Architect's notes
- Layer independent defenses: cookie attribute, token, origin check and no state change on
GETshould each be able to stop the attack alone. - Trust origins, not sites, if any subdomain hosts user content.
- Send framing headers on every page with an action.
Common mistakes
- Relying on
SameSitealone, including the browser's default. - Changing state on
GET. - A naive double-submit cookie where a subdomain can set cookies.
- Treating CORS as protection, or checking only the content type.
- Trusting
Origin: nullor a missing header, or comparing origins by prefix. - Framing headers in a
metaelement, orALLOW-FROM.
Key takeaways
- CSRF works because the browser attaches the cookie whichever page caused the request.
SameSitestops the cookie cross-site (Laxstill allows top-levelGETs) but trusts the whole site.- Tokens prove the request came from your page; the signed version survives cookie injection.
Origin,RefererandSec-Fetch-Sitesay where a request came from; never trustnullor a missing header without a fallback.- CORS is not a defense, and
frame-ancestors(withX-Frame-Options) stops clickjacking, as headers, notmeta. - Never change state on
GET, and fix XSS first.
Practice exercises
Exercise 1 — Starter (45 min): For each lab scenario, predict the layered column before reading it, then explain row C in one sentence.
Exercise 2 — Intermediate (2 hours): Add a scenario where the attacker is a sibling subdomain and the shop uses fm-same plus a token, and test it.
Exercise 3 — Advanced (half day): Audit an application you know: list each state-changing endpoint, its method, how it authenticates and which defenses apply.
Related reading
In this course:
- Cross-Site Scripting (XSS) and Its Defenses, the bug that defeats every defense here.
- The Same-Origin Policy and CORS, origins, sites and what a page may read.
- CORS in Practice: Preflights, Credentials and Debugging, why a preflight stops some forged requests.
Official documentation
- OWASP: Cross-Site Request Forgery Prevention Cheat Sheet, the patterns and their limits.
- OWASP: Clickjacking Defense Cheat Sheet, framing headers, frame-busting and SameSite.
- MDN: Cross-site request forgery (CSRF), the attack and the defenses.
- MDN: Set-Cookie, the SameSite attribute.
- web.dev: Protect your resources from web attacks with Fetch Metadata, the resource isolation policy.
- MDN: Content-Security-Policy frame-ancestors and X-Frame-Options.