Design a CSRF token service
Design a CSRF defence as a small service: HMAC-signed tokens bound to the session, constant-time verification, a middleware that checks Fetch Metadata and Origin first, and the edge cases (login CSRF, GET with side effects, subdomains) that tokens alone miss.
01Understand the problem
- Explain why cookies plus ambient authority make CSRF possible
- Build a session-bound HMAC token and verify it in constant time
- Use Fetch Metadata (
Sec-Fetch-Site) and Origin as a first, cheap layer - Handle login CSRF, state-changing GETs and same-site attackers
What they probe: what an attacker can and cannot do cross-site, why a random cookie alone (naive double submit) is weak, what binds the token to the user, how SPAs send it, and where SameSite falls short. Where candidates slip: tokens not tied to a session, == comparison, skipping the check on JSON endpoints 'because forms cannot send JSON', and GET handlers that change state.
Cross-site request forgery works because the browser attaches cookies to requests no matter which site started them. A hidden form on evil.example that posts to bank.example/transfer arrives with the victim's session cookie. The attacker cannot read the response or the victim's cookies, so the defence is to require something an attacker's page cannot know or forge: a secret token, or headers the browser sets and a page cannot.
issue(sessionId)returns a token to embed in forms or return to the SPA.verify(sessionId, token)is true only for a token issued for that session.- Middleware skips safe methods (GET, HEAD, OPTIONS), which must never change state.
- For unsafe methods it refuses
Sec-Fetch-Site: cross-site, checks Origin when present, then requires a valid token. - Tokens do not need server storage.
| Defence | Stops | Gaps |
|---|---|---|
| SameSite=Lax cookie | Most cross-site POSTs in modern browsers | Same-site attackers (sibling subdomains), top-level GETs, old browsers |
| Fetch Metadata check | Cross-site requests from browsers that send it (all current major ones) | Same-site requests; requests without the header need a fallback |
| Origin check | Requests whose Origin is not yours | Some requests omit Origin; must allow-list exact origins |
| Session-bound token | Any request without the secret | XSS can read it; needs plumbing into every form or client |
02Interfaces first
export interface CsrfService {
/** Stateless: random nonce plus HMAC over (session id, nonce). Safe to issue per page or per session. */
issue(sessionId: string): string;
verify(sessionId: string, token: string | undefined): boolean;
}
export interface CsrfConfig {
key: Buffer; // 32 bytes from the secrets manager; rotating it invalidates open forms
allowedOrigins: readonly string[]; // exact, e.g. "https://app.example.com"
headerName: string; // "x-csrf-token" for fetch calls
formField: string; // "_csrf" for HTML forms
}In naive double submit, the server only checks that a cookie and a form field match. An attacker who can write a cookie for your domain (a sibling subdomain, an HTTP page on the same host) sets both to a value they choose. An HMAC over the session id means a token is only valid for the session it was issued to, and only the server holds the key.
03Tokens and middleware
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
const TOKEN_RE = /^([A-Za-z0-9_-]{22})\.([A-Za-z0-9_-]{43})$/; // 16-byte nonce . 32-byte MAC, base64url
export class HmacCsrfService implements CsrfService {
constructor(private readonly key: Buffer) {
if (key.length < 32) throw new RangeError("CSRF key must be at least 32 bytes");
}
private mac(sessionId: string, nonce: string): Buffer {
// Length-prefix the session id so (session, nonce) pairs cannot be shifted into each other.
return createHmac("sha256", this.key).update(sessionId.length + ":" + sessionId + ":" + nonce).digest();
}
issue(sessionId: string): string {
if (!sessionId) throw new Error("a CSRF token needs a session; create a pre-login session first");
const nonce = randomBytes(16).toString("base64url");
return nonce + "." + this.mac(sessionId, nonce).toString("base64url");
}
verify(sessionId: string, token: string | undefined): boolean {
if (!sessionId || !token) return false;
const m = TOKEN_RE.exec(token);
if (!m) return false;
const given = Buffer.from(m[2], "base64url");
return given.length === 32 && timingSafeEqual(given, this.mac(sessionId, m[1]));
}
}import type { Request, Response, NextFunction } from "express";
const SAFE = new Set(["GET", "HEAD", "OPTIONS"]);
export function csrfMiddleware(svc: CsrfService, cfg: CsrfConfig, sessionIdOf: (req: Request) => string | undefined) {
const origins = new Set(cfg.allowedOrigins);
return (req: Request, res: Response, next: NextFunction): void => {
if (SAFE.has(req.method)) return next();
const site = req.get("sec-fetch-site");
if (site === "cross-site") { res.status(403).json({ error: "cross-site request refused" }); return; }
const origin = req.get("origin");
if (origin !== undefined && origin !== "null" && !origins.has(origin)) {
res.status(403).json({ error: "origin not allowed" }); return;
}
if (origin === "null") { res.status(403).json({ error: "opaque origin refused" }); return; } // sandboxed iframes, some redirects
const token = req.get(cfg.headerName) ?? (typeof req.body?.[cfg.formField] === "string" ? req.body[cfg.formField] : undefined);
const sid = sessionIdOf(req);
if (!sid || !svc.verify(sid, token)) { res.status(403).json({ error: "missing or invalid CSRF token" }); return; }
next();
};
}Single-page apps fetch the token once (from a JSON endpoint or a meta tag rendered with the page) and send it in x-csrf-token on every unsafe request. A cross-origin page cannot add a custom header to a credentialed request without a CORS preflight that your server will refuse, which is a second barrier. Server-rendered forms put it in a hidden _csrf field.
04Edge cases and tests
| Edge case | Risk | Handling |
|---|---|---|
| Login CSRF | Attacker logs the victim into the attacker's account; the victim then saves card details there | Create an anonymous pre-login session and require a token on the login form |
| GET that changes state | <img src=/account/delete> needs no token | Make it POST; safe methods must be side-effect free |
| JSON-only endpoints | text/plain form posts can carry JSON-looking bodies | Check the token on every unsafe method regardless of content type |
| Token in URL | Leaks via Referer, logs and history | Header or body only |
| Session rotation at login | The token issued before login no longer verifies | Issue a new token with the new session; the pre-login token is only for the login form |
| XSS | Script reads the token and sends a valid request | CSRF defences cannot stop XSS; fix it and add CSP |
CORS controls who can read responses. A simple cross-site form POST is sent and processed without any preflight; the attacker just cannot see the result, and for a transfer they do not need to.
import { describe, it, expect } from "vitest";
import express from "express";
import request from "supertest";
const svc = new HmacCsrfService(Buffer.alloc(32, 7)); // test key only
describe("HmacCsrfService", () => {
it("accepts a token only for the session it was issued to", () => {
const t = svc.issue("sess-A");
expect(svc.verify("sess-A", t)).toBe(true);
expect(svc.verify("sess-B", t)).toBe(false);
});
it("rejects tampering and junk", () => {
const t = svc.issue("sess-A");
const i = 23; // first MAC character: high bits, never padding
const flipped = t.slice(0, i) + (t[i] === "A" ? "B" : "A") + t.slice(i + 1);
expect(svc.verify("sess-A", flipped)).toBe(false);
expect(svc.verify("sess-A", "x.y")).toBe(false);
expect(svc.verify("sess-A", undefined)).toBe(false);
});
});
describe("csrfMiddleware", () => {
const cfg: CsrfConfig = { key: Buffer.alloc(32, 7), allowedOrigins: ["https://app.example.com"], headerName: "x-csrf-token", formField: "_csrf" };
const app = express();
app.use(express.json());
app.use(csrfMiddleware(svc, cfg, (req) => req.get("x-test-session")));
app.post("/transfer", (_req, res) => { res.json({ ok: true }); });
it("refuses cross-site requests before looking at the token", async () => {
const r = await request(app).post("/transfer").set("sec-fetch-site", "cross-site").set("x-test-session", "s1").set("x-csrf-token", svc.issue("s1"));
expect(r.status).toBe(403);
});
it("allows a same-origin request with a valid token", async () => {
const r = await request(app).post("/transfer").set("sec-fetch-site", "same-origin").set("origin", "https://app.example.com")
.set("x-test-session", "s1").set("x-csrf-token", svc.issue("s1"));
expect(r.status).toBe(200);
});
it("refuses a missing token", async () => {
const r = await request(app).post("/transfer").set("x-test-session", "s1");
expect(r.status).toBe(403);
});
});05Extensions, follow-ups, how to say it
- Key rotation: accept tokens under the current and previous key for one session lifetime, issue only under the current one.
- Per-request tokens: issuing a fresh nonce per form is free with this design; it limits the value of a token leaked from one page but breaks the back button for some flows.
- Framework support: many frameworks ship this (Django, Rails, Spring Security); configure and test theirs before writing your own.
- Non-browser clients: API clients that authenticate with a bearer header, not cookies, are not exposed to CSRF and can skip it.
Q1Why check Sec-Fetch-Site if you have tokens?+
It is cheap, needs no plumbing and blocks the whole class for modern browsers, including endpoints someone forgot to wire a token into. Tokens cover older browsers and same-site cases.
Q2Can the attacker fetch a token from your token endpoint cross-site?+
They can make the request, but the same-origin policy stops their page reading the response unless your CORS policy allows their origin with credentials, which it must not.
Q3Does SameSite=Lax make tokens unnecessary?+
Not fully. Lax still sends cookies on top-level GET navigations, does not separate same-site subdomains, and depends on browser behaviour. It is an excellent extra layer.
"Unsafe methods pass three checks. If Sec-Fetch-Site says cross-site I refuse; if Origin is present it must be an exact allowed origin; then a token must verify. The token is a random nonce plus an HMAC over the length-prefixed session id and nonce with a server key, so it needs no storage, is bound to one session and is compared in constant time. SPAs send it in a header, forms in a hidden field. Login forms use a pre-login session so login CSRF is covered, and GETs never change state."
A site uses naive double submit: it checks that a `csrf` cookie equals a `csrf` form field, both random and not tied to the session. An attacker controls `blog.example.com`, a sibling of `app.example.com`. What can they do?
Related lessons
- The bugs that actually shipSecEng · Application Security & DevSecOpsFree
- Cross-origin isolation, CORS and Fetch MetadataSecEng · Browser & web platform securityFree
- Identity: authentication, authorisation and tokensSecEng · Foundations of Security EngineeringFree
- Design a CSP violation report collectorLLD · Problems: detection & enforcement componentsPro