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.

● MediumFREEBy ·Design problem·14 min read·Beginner → Intermediate
CSRFsynchroniser tokensigned double submitSameSiteFetch MetadataOrigin header

01Understand the problem

✓What you will learn
  • 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
◎Interview radar

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.

  1. issue(sessionId) returns a token to embed in forms or return to the SPA.
  2. verify(sessionId, token) is true only for a token issued for that session.
  3. Middleware skips safe methods (GET, HEAD, OPTIONS), which must never change state.
  4. For unsafe methods it refuses Sec-Fetch-Site: cross-site, checks Origin when present, then requires a valid token.
  5. Tokens do not need server storage.
DefenceStopsGaps
SameSite=Lax cookieMost cross-site POSTs in modern browsersSame-site attackers (sibling subdomains), top-level GETs, old browsers
Fetch Metadata checkCross-site requests from browsers that send it (all current major ones)Same-site requests; requests without the header need a fallback
Origin checkRequests whose Origin is not yoursSome requests omit Origin; must allow-list exact origins
Session-bound tokenAny request without the secretXSS can read it; needs plumbing into every form or client

02Interfaces first

The contractts
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
}
iWhy bind the token to the session

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

HmacCsrfServicets
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]));
  }
}
Middlewarets
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.

▭On the whiteboard · Design choices4 points
01
token
16-byte nonce plus HMAC-SHA256(key, len:sessionId:nonce); stateless
02
verify
strict format, constant-time compare, false for no session
03
layers
Sec-Fetch-Site, then Origin allow-list, then token
04
scope
every unsafe method; safe methods must have no side effects

04Edge cases and tests

Edge caseRiskHandling
Login CSRFAttacker logs the victim into the attacker's account; the victim then saves card details thereCreate an anonymous pre-login session and require a token on the login form
GET that changes state<img src=/account/delete> needs no tokenMake it POST; safe methods must be side-effect free
JSON-only endpointstext/plain form posts can carry JSON-looking bodiesCheck the token on every unsafe method regardless of content type
Token in URLLeaks via Referer, logs and historyHeader or body only
Session rotation at loginThe token issued before login no longer verifiesIssue a new token with the new session; the pre-login token is only for the login form
XSSScript reads the token and sends a valid requestCSRF defences cannot stop XSS; fix it and add CSP
!CORS is not a CSRF defence on its own

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.

vitestts
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.

“How to say it in the room

"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."

Test yourself

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?

Finished this one?
Tick it and it shows as done on the roadmap and the course.