CSRF Tokens: When SameSite Is Not Enough
On this page
Learning Objective
Implement the synchronizer token and double-submit cookie patterns correctly, explain the subdomain weakness in naive double-submit, and identify the specific residual cases that justify keeping tokens even with SameSite=Lax in force.
Concept Explanation
CSRF exists because of the asymmetry established in this course's second lesson: a cross-site request is dispatched and processed even though its response cannot be read. The attacker never needs to see anything; they need the server to act. Historically the defense was an unguessable token, and although SameSite=Lax now blocks the classic form-post attack automatically, tokens remain necessary for a set of cases that SameSite does not reach.
The synchronizer token pattern is the strongest form. The server generates a random token, stores it in the user's server-side session, and embeds it in every form or exposes it to the front end. Every state-changing request must present it, and the server compares the presented value against the one in the session, using a constant-time comparison. Because the token lives in server-side state, the attacker cannot obtain or predict it, and because it is not a cookie, it is not attached automatically to cross-site requests. The cost is server-side state and some awkwardness with multiple tabs and long-lived pages, which is usually handled by scoping the token per session rather than per form.
The double-submit cookie pattern avoids server-side state. The server sets a random value in a cookie and the client sends the same value in a request header or body field; the server verifies only that the two match. This works because an attacker's cross-site page can cause the cookie to be sent but cannot read it to put the matching value in the header. The naive version has a real weakness, though: an attacker who can set cookies for your domain, typically from a compromised or user-content sibling subdomain, can write both halves and satisfy the check. The signed double-submit variant fixes this by making the cookie value an HMAC over the session identifier keyed by a server secret, so a value the attacker chooses cannot validate.
Two supporting checks are cheap and worth adding. The Origin request header is present on all cross-origin requests and on all POST requests including same-origin ones in modern browsers, so comparing it against an expected value is a strong server-side signal; the older Referer header is a weaker fallback since it is frequently stripped by privacy settings and proxies. The newer Sec-Fetch-Site request header, part of the Fetch Metadata family, states directly whether a request is same-origin, same-site, cross-site, or user-initiated, and rejecting cross-site requests to state-changing endpoints based on it is a concise defense that requires no token at all in supporting browsers.
So which residual cases justify keeping tokens when SameSite=Lax is already deployed? First, state-changing GET endpoints, which Lax does not protect at all, though the correct fix is to eliminate them. Second, same-site attackers: a compromised or user-content sibling subdomain is same-site by definition, so SameSite provides no protection against it and only a token bound to server-side state does. Third, cookies that must be SameSite=None for legitimate third-party embedding. Fourth, older browsers and non-browser clients without SameSite support. Fifth, Chrome's two-minute Lax-plus-POST window for defaulted cookies. Defense in depth here is cheap, and the failure mode of omitting it is silent.
| Defense | Server-side state | Stops a same-site subdomain attacker | Main weakness |
|---|---|---|---|
| SameSite=Lax cookie | None | No; a sibling subdomain is same-site | Top-level cross-site GET still carries the cookie |
| Synchronizer token | Required | Yes | State management across tabs and long-lived pages |
| Naive double-submit cookie | None | No; the attacker can set both halves | Cookie-writing from a sibling subdomain |
| Signed double-submit (HMAC) | A secret key only | Yes | Requires correct binding to the session identifier |
| Origin header check | None | Yes, if the expected origin is exact | Needs care with legitimate cross-origin front ends |
| Sec-Fetch-Site check | None | Yes | Absent in older browsers; use as a layer, not alone |
Worked Example: Signed Double-Submit Plus an Origin Check
The implementation below combines a stateless token that a sibling subdomain cannot forge with a server-side origin check, which together cover every residual case listed above without requiring server-side session storage for the token itself.
const crypto = require('crypto');
const CSRF_KEY = process.env.CSRF_KEY; // server secret, never shipped
const ALLOWED_ORIGINS = new Set(['https://app.example.com']);
// Bind the token to the session so a value the attacker picks cannot validate
function issueCsrfToken(sessionId) {
const nonce = crypto.randomBytes(16).toString('base64url');
const mac = crypto.createHmac('sha256', CSRF_KEY)
.update(`${sessionId}.${nonce}`).digest('base64url');
return `${nonce}.${mac}`;
}
function verifyCsrfToken(sessionId, token) {
const [nonce, mac] = String(token || '').split('.');
if (!nonce || !mac) return false;
const expected = crypto.createHmac('sha256', CSRF_KEY)
.update(`${sessionId}.${nonce}`).digest('base64url');
const a = Buffer.from(mac), b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b); // constant time
}
app.use((req, res, next) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
// Layer 1 - Fetch Metadata, where available
const site = req.headers['sec-fetch-site'];
if (site && site !== 'same-origin') return res.status(403).end();
// Layer 2 - Origin header, exact match against an allowlist
const origin = req.headers.origin;
if (origin && !ALLOWED_ORIGINS.has(origin)) return res.status(403).end();
// Layer 3 - signed double-submit token bound to this session
if (!verifyCsrfToken(req.session.id, req.headers['x-csrf-token'])) {
return res.status(403).end();
}
next();
});
// The cookie carrying the same value, readable by the front end by design
// Set-Cookie: __Host-csrf=<token>; Secure; Path=/; SameSite=StrictReal-World Examples
- The 2008 paper "Robust Defenses for Cross-Site Request Forgery" by Barth, Jackson, and Mitchell introduced the systematic analysis of CSRF defenses still used today, documenting live vulnerabilities at ING Direct that allowed fund transfers, at YouTube that allowed adding videos to a victim's favorites, and at the New York Times that exposed subscriber email addresses, and it is the work that established the Origin header as a practical server-side defense.
- A widely reported Gmail vulnerability in 2007 allowed an attacker to add a mail filter to a victim's account through a forged cross-origin request, silently forwarding incoming mail to an attacker-controlled address; the attack required only that the victim visit a page while logged in, needed no response to be read, and is the standard illustration of why a state change must never be reachable without a token or an equivalent origin check.
Review Questions & Answers
The pattern only verifies that the cookie value and the submitted value match, without binding either to server-side state. An attacker on a sibling subdomain can set a cookie for the parent domain, so they choose the value, place the same value in their forged request's header, and the comparison succeeds. Signing the cookie value as an HMAC over the session identifier with a server-held key fixes this, because a value the attacker invents will not verify against the victim's session.
Origin is sent on all cross-origin requests and on all POST requests in modern browsers, contains only the scheme, host, and port so it leaks no path or query information, and is therefore not stripped by privacy tooling the way Referer routinely is. Referer is frequently removed by browser settings, proxies, and Referrer-Policy configurations, so a check that requires it will either fail open when it is absent or break legitimate traffic when it is not.
First, a same-site attacker on a compromised or user-content sibling subdomain, since such a host is same-site by definition and SameSite offers no protection against it. Second, cookies that must be set to SameSite=None for legitimate third-party embedding or federated flows, which are entirely unprotected. Third, any state-changing GET endpoint, which Lax still permits cross-site, along with Chrome's two-minute Lax-plus-POST window for cookies that were defaulted rather than explicitly marked.
Because an ordinary string comparison returns as soon as it finds a differing byte, so the time it takes correlates with how many leading bytes matched. An attacker able to submit many guesses and measure response timing can reconstruct a valid token byte by byte. A constant-time comparison takes the same time regardless of where the values differ, removing that signal, and the same reasoning applies to every secret comparison, including signature and MAC verification.