01 //Introduction
Cross-Site Request Forgery (CSRF, sometimes XSRF or "session riding") is a client-side trust confusion bug. A user is authenticated to your application; a different origin convinces the user's browser to issue a state-changing request to your application; the browser attaches the session cookie automatically; your server sees a properly-authenticated request and acts on it. The attacker never touches the session cookie, never reads any response, and never needs the victim to do more than open a page. The flaw is twenty-five years old, has its own dedicated CWE-352, and still appears in fresh advisories every quarter, because the underlying browser behaviour (send cookies on cross-origin requests by default) was only partially fixed by the SameSite cookie rollout in 2020.
The bug lives at the boundary between two browser features that, individually, are correct. Cookies are ambient authority: once set, they ride along on every request to the matching origin, regardless of which page issued the request. Forms and fetch() calls are allowed to target cross-origin URLs. Combined, the browser will happily issue an authenticated request to your application from any other tab the user has open. Modern defenses, SameSite cookies, CSRF tokens, Origin checks, all exist to break this default trust and force the server to verify that the request was intended by the user.
SameSite=Lax in 2020, much of the security community declared CSRF dead. It is not. Lax cookies are sent on top-level cross-site GET navigations, so any state-changing GET endpoint is still exposed. Lax is also bypassed by same-site subdomain takeovers, by browsers without the default (older Safari, embedded webviews, many mobile browsers in restricted markets), and by any flow where the developer set SameSite=None to support third-party embedding. Tokens and Origin checks remain mandatory for real defense; SameSite is a useful backstop, not a replacement.OWASP catalogues CSRF in the CSRF Prevention Cheat Sheet, and the bug class dropped out of the OWASP Top 10 between 2017 and 2021 precisely because framework defaults improved, not because the bug disappeared. The defensive recipe is identical across languages: protect every state-changing endpoint with a token tied to the session, verify the request origin, set cookies to SameSite=Lax at minimum, and never allow GET to mutate state. This module walks through the attack surface, the canonical payloads, the per-framework fix, and the modern subtleties (BREACH on tokens, JSON CSRF, login CSRF) that still bite teams in 2026.
A banking app sets its session cookie with the default SameSite=Lax. The /transfer endpoint accepts POST with form data and no CSRF token, relying on SameSite to block cross-origin POSTs. Why is this still vulnerable?
02 //The Attack Flow
Every CSRF exploit follows the same four-stage flow: the victim authenticates to the target application (a session cookie is now stored in their browser), the victim visits or is redirected to an attacker-controlled page on a different origin, that page causes the browser to issue a state-changing request to the target (via a hidden form, an image tag, a fetch() call, or a top-level navigation), and the browser, following its default cookie behaviour, attaches the session cookie. The server sees an authenticated request and performs the action. The attacker never reads the response; they do not need to. The damage is the side effect.
bank.appevil.tld renders a hidden form or fetch() to bank.appPOST /transfer succeeds; the user never clicked itCSRF is not an authentication bug; the user is correctly authenticated. It is an authorisation bug at the request boundary: the server cannot tell whether the state-changing request was intended by the user or smuggled in by another origin that the browser was tricked into loading. Every CSRF defense, tokens, SameSite, Origin checks, is a way to prove intent before the cookie is honoured.
The shape of a realistic exploit depends on the request the attacker needs to issue. HTML forms can submit POST with application/x-www-form-urlencoded, multipart/form-data, or text/plain bodies cross-origin without a preflight, so any endpoint that accepts those content types is reachable. fetch() and XMLHttpRequest can issue any method with any body, but cross-origin requests with custom headers or JSON content types trigger a CORS preflight, which the attacker cannot satisfy unless your CORS policy is misconfigured. img, script, link, and iframe tags can issue cross-origin GETs.
CSRF Attack Surfaces in Real Applications
| Endpoint shape | Why it is exposed |
|---|---|
| POST with form-urlencoded body | Native HTML form, no preflight, cookies attached |
| GET that changes state | Any tag (img/link/iframe) triggers it; SameSite=Lax allows top-level navigation |
| POST with text/plain body | No preflight; JSON-like payloads can be smuggled if the server parses lenient bodies |
| POST with multipart/form-data | File-upload endpoints reachable from a form with enctype=multipart |
| Endpoints behind method-override (?_method=DELETE) | Attacker uses POST with the override param; bypasses "POST-only" assumption |
| CORS-with-credentials misconfiguration | Server reflects Origin into Access-Control-Allow-Origin with Allow-Credentials: true, opening every endpoint |
| Login endpoints (login CSRF) | Attacker forces victim to log in as the attacker, mixing identities in the session |
| Logout endpoints | Forced logout used as nuisance or to mask a phishing attempt |
| JSON APIs without preflight enforcement | If the server accepts text/plain or form-urlencoded as JSON, the preflight protection is moot |
<img src="https://app.tld/account/delete"> on any page the victim opens triggers a cross-origin GET with cookies attached. If /account/delete mutates state on GET, the account is gone the moment the victim views the page. Every "no body, no harm" assumption breaks on GET endpoints that perform writes. The OWASP rule, GET must be safe and idempotent, is not a style preference; it is a CSRF mitigation.1<!-- Hosted at https://evil.tld/promo.html
2 The victim is signed in to bank.app in another tab.
3 They open this page from a phishing email.
4 The form auto-submits with the session cookie attached. -->
5<!doctype html>
6<html>
7 <body>
8 <h1>You won a prize!</h1>
9 <form id="x" action="https://bank.app/transfer" method="POST">
10 <input type="hidden" name="to" value="attacker-account-1234" />
11 <input type="hidden" name="amount" value="5000" />
12 </form>
13 <script>document.getElementById('x').submit();</script>
14 </body>
15</html>
16
17<!-- Variant 1, image tag for a GET endpoint that mutates state -->
18<img src="https://bank.app/account/close?confirm=1" width="0" height="0" />
19
20<!-- Variant 2, JSON CSRF where the server accepts text/plain
21 This is a CORS-preflight-free request, no Content-Type negotiation. -->
22<form action="https://bank.app/api/transfer" method="POST" enctype="text/plain">
23 <input name='{"to":"attacker","amount":5000,"x":"' value='"}' />
24</form>A team argues their JSON API is safe from CSRF because browsers send a CORS preflight for application/json requests, which their server rejects. A pentester demonstrates a successful CSRF anyway. What did the team miss?
03 //Payload Anatomy & Token Bypasses
The attacker's payload is constrained by what the browser will let cross-origin code do without triggering a CORS preflight. The "simple request" set, GET, HEAD, and POST with form-urlencoded, multipart, or text/plain bodies, is reachable from a plain HTML form on any page. Anything outside that set (custom methods, custom headers, JSON content type) preflights, and a correctly-configured CORS policy refuses the preflight. The defender's mistake is usually to add a token check, then forget one of the bypass paths: an alternate verb, a sibling endpoint, a method-override middleware, or a same-origin XSS that reads the token directly.
SameSite=LaxorStricton the session cookie- Synchronizer token or double-submit token on every state-changing endpoint
Origin/Sec-Fetch-Sitevalidation on the server- Reject
POST,PUT,PATCH,DELETEwithout a CSRF check
- Custom request header (
X-Requested-With) for JSON APIs - Re-authentication or step-up for high-value actions
- Short session lifetime + idle timeout on sensitive routes
__Host-cookie prefix to lock the path and scope- CORS allow-list locked to your own origins, with credentials guarded
SameSite alone is not enough. Lax does not cover top-level GET-triggered side effects, browsers older than 2020 ignore it, and a same-site subdomain XSS makes it useless. The layered defense is: SameSite plus a token plus an Origin check. If you remove any one of the three, the next regression in another layer becomes exploitable.
Payload Catalogue, What an Attacker Actually Sends
| Payload pattern | Effect | Mitigation that defeats it |
|---|---|---|
| Cross-origin POST with session cookie attached | Synchronizer or double-submit token; Origin check | |
| Cross-origin GET with cookie; works against any state-changing GET | Never mutate state on GET; require POST and a token | |
| JSON CSRF without triggering a CORS preflight | Strict Content-Type check on the server (require application/json); reject text/plain | |
| POST /api/x?_method=DELETE | Method-override middleware turns POST into DELETE, bypassing "DELETE requires preflight" | Apply token + Origin check before method-override middleware, or remove the middleware |
| Login form posted from evil.tld (login CSRF) | Victim is silently logged into attacker's account; subsequent victim actions are attributed to attacker | CSRF-protect the login endpoint too; pre-session token bound to the login form |
| fetch("/api/x", { credentials: "include", mode: "no-cors" }) | Fire-and-forget cross-origin write; response is opaque but the side effect lands | Token + Origin check on the endpoint; never rely on attacker being unable to read the response |
| Subdomain XSS reads token from main app | XSS on staging.app.tld reads CSRF token via shared cookie, then submits to app.tld | __Host- cookie prefix; cookie path/domain scoping; treat subdomains as untrusted |
| BREACH-style compression oracle leaks token | gzip + reflected token + attacker-controlled query parameter leaks the token byte by byte | Rotate token per request, or disable compression on responses that include the token |
1<!-- 1. Classic auto-submitting form, the canonical 2002 attack. -->
2<form id="f" action="https://app.tld/email/change" method="POST">
3 <input name="email" value="attacker@evil.tld">
4</form>
5<script>f.submit()</script>
6
7<!-- 2. JSON-via-text-plain bypass, defeats lenient JSON parsers. -->
8<form action="https://app.tld/api/role" method="POST" enctype="text/plain">
9 <input name='{"role":"admin","_pad":"' value='"}'>
10</form>
11<!-- The body becomes: {"role":"admin","_pad":"="} (valid JSON) -->
12
13<!-- 3. Method-override bypass, defeats DELETE-requires-preflight assumption. -->
14<form action="https://app.tld/account?_method=DELETE" method="POST">
15</form>A reviewer adds CSRF tokens to all POST endpoints. A teammate notes that the same endpoints also accept PUT and DELETE via fetch from the SPA, and the token check is only applied in the POST handler. What is the correct fix?
04 //Mitigation Patterns
There are three correct defenses, layered. Use a synchronizer token (or its stateless cousin, the signed double-submit token) on every state-changing endpoint; set session cookies to SameSite=Lax at minimum with the __Host- prefix; and validate the Origin header (falling back to Referer) on every state-changing request. None of these on its own closes the class. SameSite leaks via subdomain XSS and embedded browsers. Tokens leak via BREACH or are forgotten on new endpoints. Origin checks fail on requests where the header is missing. Together, any two surviving any one regression keep the attack out.
Mitigation Options at a Glance
| Strategy | How | When to use |
|---|---|---|
| Synchronizer Token Pattern | Server stores a per-session random token; client sends it in a hidden form field or X-CSRF-Token header; server compares constant-time | Default for server-rendered apps; the gold-standard defense |
| Signed double-submit cookie | Server sets a token in a cookie AND requires it in a header; tokens are HMAC-signed and bound to the session ID | Stateless backends, SPAs, edge functions; avoids server-side session storage |
| SameSite cookie attribute | Set session cookie with SameSite=Lax (default) or Strict; combined with __Host- prefix | Always; backstop defense even when tokens are present |
| Origin / Sec-Fetch-Site header check | Server rejects state-changing requests whose Origin (or Sec-Fetch-Site) does not match the application origin | Always; cheap, robust, browser-enforced |
| Custom request header (X-Requested-With) | Server requires a custom header that cross-origin simple requests cannot set without a preflight | JSON APIs; a useful belt-and-braces layer, NOT a sole defense |
| Re-authentication for sensitive actions | Require password / MFA / step-up for high-value actions (transfers, deletes, permission grants) | Anywhere the blast radius of a single CSRF would be severe |
1// lib/csrf.ts, signed double-submit pattern.
2//
3// Strategy: derive a per-session HMAC token, send it in a non-HttpOnly
4// cookie AND require it in the X-CSRF-Token header on state-changing
5// requests. Compare constant-time. The HMAC binds the token to the
6// session so the attacker cannot mint or replay tokens.
7
8import crypto from 'crypto';
9import type { Request, Response, NextFunction } from 'express';
10
11const SECRET = process.env.CSRF_SECRET!; // 32+ bytes from a secure store
12const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
13const TRUSTED_ORIGINS = new Set([
14 'https://app.tld',
15 'https://www.app.tld',
16]);
17
18function sign(sessionId: string): string {
19 const nonce = crypto.randomBytes(16).toString('hex');
20 const mac = crypto
21 .createHmac('sha256', SECRET)
22 .update(`${sessionId}.${nonce}`)
23 .digest('hex');
24 return `${nonce}.${mac}`;
25}
26
27function verify(sessionId: string, token: string): boolean {
28 const [nonce, mac] = token.split('.');
29 if (!nonce || !mac) return false;
30 const expected = crypto
31 .createHmac('sha256', SECRET)
32 .update(`${sessionId}.${nonce}`)
33 .digest('hex');
34 // constant-time compare, prevents timing leaks
35 const a = Buffer.from(mac, 'hex');
36 const b = Buffer.from(expected, 'hex');
37 return a.length === b.length && crypto.timingSafeEqual(a, b);
38}
39
40export function csrfMiddleware(req: Request, res: Response, next: NextFunction) {
41 const sessionId = req.session?.id;
42 if (!sessionId) return next(); // unauthenticated; no session to ride
43
44 // Issue a fresh token on every request, set as readable cookie.
45 // The cookie is NOT HttpOnly because the SPA needs to read it.
46 // It IS SameSite=Strict and __Host- prefixed to lock the scope.
47 if (!req.cookies['__Host-csrf']) {
48 res.cookie('__Host-csrf', sign(sessionId), {
49 secure: true,
50 sameSite: 'strict',
51 path: '/',
52 });
53 }
54
55 if (SAFE_METHODS.has(req.method)) return next();
56
57 // 1. Origin check, cheap and robust
58 const origin = req.get('origin') ?? req.get('referer');
59 if (!origin || !TRUSTED_ORIGINS.has(new URL(origin).origin)) {
60 return res.status(403).json({ error: 'origin mismatch' });
61 }
62
63 // 2. Token check
64 const headerToken = req.get('x-csrf-token');
65 const cookieToken = req.cookies['__Host-csrf'];
66 if (!headerToken || headerToken !== cookieToken || !verify(sessionId, headerToken)) {
67 return res.status(403).json({ error: 'csrf token invalid' });
68 }
69
70 next();
71}
72
73// Mount as global middleware; never per-route.
74// app.use(csrfMiddleware);=== or strcmp leaks the matched-prefix length via timing. Modern CPUs make the leak small but real, and CSRF tokens are short-lived enough that even a few bits per attempt matter. Use crypto.timingSafeEqual in Node, hmac.compare_digest in Python, MessageDigest.isEqual in Java, hash_equals in PHP, and subtle.ConstantTimeCompare in Go. Same rule as for password and HMAC verification.1# settings.py, the secure default. Django ships CSRF protection
2# enabled; the work is making sure you do not opt out.
3
4MIDDLEWARE = [
5 "django.middleware.security.SecurityMiddleware",
6 "django.contrib.sessions.middleware.SessionMiddleware",
7 "django.middleware.common.CommonMiddleware",
8 "django.middleware.csrf.CsrfViewMiddleware", # MUST be present
9 "django.contrib.auth.middleware.AuthenticationMiddleware",
10]
11
12# Cookie hardening, the __Host- prefix requires Secure + Path=/ + no Domain.
13SESSION_COOKIE_SECURE = True
14SESSION_COOKIE_HTTPONLY = True
15SESSION_COOKIE_SAMESITE = "Lax"
16CSRF_COOKIE_SECURE = True
17CSRF_COOKIE_SAMESITE = "Lax"
18CSRF_COOKIE_NAME = "__Host-csrftoken" # locks path / forbids Domain
19
20# Trust ONLY your own origins. Never wildcard.
21CSRF_TRUSTED_ORIGINS = [
22 "https://app.tld",
23 "https://www.app.tld",
24]
25
26# Templates: every form must include {% csrf_token %}
27# Class-based views are protected automatically.
28# DO NOT decorate views with @csrf_exempt unless you have an alternative defense.
29
30# For DRF (Django REST Framework) JSON APIs:
31# Use SessionAuthentication (CSRF-protected) for browser clients.
32# Use TokenAuthentication / JWT (Authorization header) for non-browser clients,
33# which are not subject to CSRF because no cookie is attached.
34
35from rest_framework.views import APIView
36from rest_framework.authentication import SessionAuthentication
37
38class TransferView(APIView):
39 authentication_classes = [SessionAuthentication] # CSRF enforced
40 def post(self, request):
41 # request.session is authenticated AND the CSRF token has been verified
42 ...1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3import org.springframework.security.config.annotation.web.builders.HttpSecurity;
4import org.springframework.security.web.SecurityFilterChain;
5import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
6import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
7import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler;
8
9@Configuration
10public class SecurityConfig {
11
12 @Bean
13 public SecurityFilterChain chain(HttpSecurity http) throws Exception {
14 // XOR handler defeats BREACH-style compression oracle leaks on the
15 // token by re-masking on every render.
16 XorCsrfTokenRequestAttributeHandler xor = new XorCsrfTokenRequestAttributeHandler();
17
18 http.csrf(csrf -> csrf
19 // Token in a cookie, readable by the SPA; double-submit pattern.
20 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
21 .csrfTokenRequestHandler(xor)
22 // Do NOT call .disable() unless you have an alternative defense.
23 );
24 return http.build();
25 }
26}
27
28// Cookie hardening (in application.yml)
29// server.servlet.session.cookie.secure=true
30// server.servlet.session.cookie.http-only=true
31// server.servlet.session.cookie.same-site=lax1// Program.cs, the secure default. AddAntiforgery is wired in by
2// AddControllersWithViews / AddRazorPages; the work is the cookie hardening.
3
4builder.Services.AddAntiforgery(options =>
5{
6 options.Cookie.Name = "__Host-X-CSRF";
7 options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
8 options.Cookie.SameSite = SameSiteMode.Lax;
9 options.Cookie.HttpOnly = true;
10 options.HeaderName = "X-CSRF-Token"; // SPA reads cookie, sets header
11});
12
13builder.Services.ConfigureApplicationCookie(options =>
14{
15 options.Cookie.Name = "__Host-Auth";
16 options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
17 options.Cookie.SameSite = SameSiteMode.Lax;
18 options.Cookie.HttpOnly = true;
19});
20
21var app = builder.Build();
22
23// Global anti-forgery filter, enforced on ALL non-safe methods.
24app.UseAntiforgery();
25
26// Controllers
27[ApiController]
28[Route("api/[controller]")]
29public class TransferController : ControllerBase
30{
31 // [ValidateAntiForgeryToken] is implicit when UseAntiforgery is mounted;
32 // explicit per-action only if you want to override.
33 [HttpPost]
34 public IActionResult Post([FromBody] TransferRequest req) => Ok();
35}
36
37// NEVER apply [IgnoreAntiforgeryToken] without an alternative defense.A team migrates from server-rendered pages to a SPA that calls a JSON API. They drop CSRF tokens, arguing 'our API uses Bearer tokens from localStorage, not cookies, so CSRF does not apply'. Are they right?
05 //Modern Subtleties: SameSite, BREACH, and JSON APIs
The defenses above close the textbook attack. The modern subtleties, the things that still produce CVEs in 2026, live in the gaps between layers: how SameSite interacts with subdomains, how token rotation interacts with compression oracles, how JSON APIs interact with lenient body parsers, and how the framework's default differs from what the framework documentation describes. A reviewer who knows only the OWASP one-pager will miss them.
Per-Surface Behaviour and Required Defense
| Surface | Subtlety | Correct defense |
|---|---|---|
| SameSite=Lax and top-level GET | Lax sends cookies on top-level navigations triggered by a user gesture; any state-changing GET is still exposed | Never mutate state on GET; require POST and a token |
| SameSite scope is per registrable domain | staging.app.tld and app.tld are "same-site"; a subdomain XSS bypasses SameSite entirely | __Host- cookie prefix; treat subdomains as untrusted; isolate sensitive cookies by exact host |
| BREACH attack on a reflected CSRF token | gzip compression + token reflected in response + attacker-controlled query param leaks the token byte by byte | Rotate token per request (Spring XorCsrfTokenRequestAttributeHandler), or disable compression on token-bearing responses |
| Lenient JSON body parsing | Express body-parser with type: "*/*" accepts text/plain; defeats the preflight-protects-JSON assumption | Require Content-Type: application/json on JSON endpoints; reject text/plain on server side |
| Method-override middleware | POST + ?_method=DELETE becomes a real DELETE inside the handler, bypassing CORS preflight expectations | Apply CSRF / Origin checks BEFORE method-override, or remove the middleware |
| CORS misconfiguration | Access-Control-Allow-Origin reflects the Origin header with Allow-Credentials: true; every endpoint is now CORS-bypassed | Allow-list explicit origins; never reflect; never combine reflection with credentials |
| Login CSRF | Victim is silently logged into the attacker's account; subsequent victim actions are attributed to attacker | Protect the login form with a pre-session token; rotate session on successful login |
| PDF / Flash / Java applet legacy issuance | Old plugins issue cross-origin requests with cookies, bypassing browser-level CSRF defenses | Drop legacy plugin support; rely on modern browser-only behaviour |
1// UNSAFE, the CSRF token is reflected unchanged in the HTML response
2// AND the response is gzip-compressed AND an attacker-controlled query
3// parameter is also reflected. The classic BREACH oracle.
4
5app.get('/profile', (req, res) => {
6 const token = req.session.csrfToken; // SAME token reused across requests
7 res.set('Content-Encoding', 'gzip');
8 res.send(`
9 <html><body>
10 <form><input name="csrf" value="${token}"></form>
11 <p>You searched for: ${req.query.q}</p> <!-- attacker controls q -->
12 </body></html>
13 `);
14});
15
16// Attack: attacker injects q = "csrf=A", "csrf=B", ... and observes
17// compressed-response-length differences. Whichever guess shares the
18// most bytes with the real token compresses smaller. Token leaks byte
19// by byte across thousands of cross-origin requests.
20
21// SAFE, the token is masked on every render with a per-response XOR pad.
22// Spring's XorCsrfTokenRequestAttributeHandler implements exactly this.
23function maskToken(rawToken) {
24 const pad = crypto.randomBytes(rawToken.length / 2);
25 const raw = Buffer.from(rawToken, 'hex');
26 const masked = Buffer.alloc(raw.length);
27 for (let i = 0; i < raw.length; i++) masked[i] = raw[i] ^ pad[i];
28 return pad.toString('hex') + masked.toString('hex');
29}
30// The wire form changes every request; BREACH cannot accumulate evidence.__Host- cookie prefix is a browser-enforced contract: the cookie must be Secure, must have Path=/, and must NOT have a Domain attribute. A cookie set with the prefix cannot be overwritten by a sibling subdomain. For session and CSRF cookies, this is the cheapest defense against the entire class of "subdomain takeover poisons the parent site" attacks. Every framework supports it; few default to it. Set it explicitly.1// UNSAFE, body-parser configured to accept any content type.
2import express from 'express';
3import bodyParser from 'body-parser';
4
5const app = express();
6app.use(bodyParser.json({ type: '*/*' })); // <-- the bug
7// Now ANY POST with a JSON-shaped body parses, including
8// text/plain bodies from cross-origin forms (no preflight).
9
10app.post('/api/role', (req, res) => {
11 if (req.user) req.user.role = req.body.role; // CSRF-able
12 res.json({ ok: true });
13});
14
15// Attacker page:
16// <form action="https://app.tld/api/role" method="POST" enctype="text/plain">
17// <input name='{"role":"admin","_x":"' value='"}'>
18// </form>
19// Body becomes: {"role":"admin","_x":"="}, valid JSON, no preflight.
20
21// SAFE, require the application/json content type, reject anything else.
22app.use(bodyParser.json({ type: 'application/json', strict: true }));
23
24// Belt-and-braces: middleware that explicitly checks Content-Type
25// on state-changing requests and rejects text/plain / multipart on JSON endpoints.
26app.use((req, res, next) => {
27 if (req.method === 'GET' || req.method === 'HEAD') return next();
28 const ct = (req.get('content-type') ?? '').split(';')[0].trim();
29 if (req.path.startsWith('/api/') && ct !== 'application/json') {
30 return res.status(415).json({ error: 'application/json required' });
31 }
32 next();
33});A bug bounty report shows that a 2-byte CSRF token leak per request is enough to recover a 32-character token in under an hour, via a BREACH oracle on a search-results page that reflects both the token and the query string, both gzip-compressed. The team's fix is to add `Cache-Control: no-store` to the response. Is that sufficient?
06 //Detection in Code Review
CSRF has a narrow, well-known surface: every state-changing endpoint, every cookie-set call, every middleware mount. Grep gets you most of the way; the rest is reading the route file to confirm the global middleware is present and not disabled per-route. The standout signal in code review is any csrf_exempt, IgnoreAntiforgeryToken, protect_from_forgery skip, or csrf({ ignoreMethods: ... }) annotation, those are explicit opt-outs and each one must justify itself.
1# Find every CSRF opt-out in the codebase. Each one needs justification.
2
3# Django
4rg -n 'csrf_exempt|@requires_csrf_token|csrf_protect|CSRF_TRUSTED_ORIGINS'
5
6# Rails
7rg -n 'protect_from_forgery|skip_before_action.*verify_authenticity_token|with: :null_session'
8
9# Spring
10rg -n '\.csrf\(.*disable|@EnableWebSecurity|CsrfTokenRepository|CsrfTokenRequestHandler'
11
12# ASP.NET
13rg -n 'IgnoreAntiforgeryToken|AddAntiforgery|UseAntiforgery|ValidateAntiForgeryToken'
14
15# Express / Node
16rg -n 'csurf|csrf\(|tiny-csrf|@fastify/csrf|csrf-csrf|cookie-parser'
17
18# Cookie hardening, SameSite + Secure + __Host-
19rg -nE 'sameSite|SameSite\s*=|__Host-|cookie.*secure'
20
21# State-changing methods without a token middleware nearby
22rg -nE '\.(post|put|patch|delete)\(|@(Post|Put|Patch|Delete)Mapping'
23
24# CORS misconfiguration smells
25rg -nE 'Access-Control-Allow-Origin.*\*|origin:\s*true|cors\(\{.*credentials.*origin.*\*'
26
27# Method-override middleware
28rg -n 'method-override|_method=|MethodOverride'
29
30# The right pattern, framework defaults present
31rg -n 'csrfMiddleware|verifyCsrf|antiforgery|CsrfViewMiddleware'SAST / Linter Coverage
| Tool | Rule | Catches |
|---|---|---|
| Semgrep | p/owasp-top-ten, p/django, p/javascript-security; csrf-* rule family | Disabled middleware, csrf_exempt decorators, missing protect_from_forgery, Express without csurf |
| CodeQL | java/csrf-protection-disabled, py/csrf-disabled, cs/csrf-protection-disabled | Spring .csrf().disable(), Django @csrf_exempt, ASP.NET [IgnoreAntiforgeryToken] |
| Snyk Code | CWE-352 / csrf rule family | Multi-language; flags disabled defaults and per-route bypasses |
| Brakeman (Rails) | CrossSiteRequestForgery | Detects skip_before_action :verify_authenticity_token and protect_from_forgery with: :null_session |
| Bandit (Python) | B703 django-mark-safe (adjacent); no direct CSRF rule | Use a custom rule that flags csrf_exempt and CSRF middleware removal |
| gosec | no dedicated rule | Custom rule for net/http handlers without a CSRF middleware on non-GET methods |
1# semgrep-rules/csrf-opt-out.yaml
2rules:
3 - id: django-csrf-exempt
4 languages: [python]
5 severity: ERROR
6 message: >-
7 @csrf_exempt removes CSRF protection from this view. Every state-
8 changing endpoint must be CSRF-protected. If this endpoint is called
9 with a non-cookie credential (Authorization: Bearer), document that
10 in a comment and add an Origin check instead.
11 pattern: |
12 @csrf_exempt
13 def $FN(...):
14 ...
15 metadata:
16 cwe: 'CWE-352'
17 owasp: 'A01:2021 - Broken Access Control'
18
19 - id: spring-csrf-disabled
20 languages: [java]
21 severity: ERROR
22 message: >-
23 Spring Security CSRF protection is disabled. This is a CSRF-class
24 vulnerability unless every state-changing endpoint uses a non-cookie
25 credential.
26 pattern-either:
27 - pattern: $H.csrf().disable()
28 - pattern: $H.csrf(csrf -> csrf.disable())
29 metadata:
30 cwe: 'CWE-352'
31
32 - id: express-cors-credentials-with-wildcard
33 languages: [javascript, typescript]
34 severity: ERROR
35 message: >-
36 CORS configured with credentials AND a permissive origin. Any site
37 can now make authenticated requests; CSRF tokens alone will not save
38 you because the browser allows reading the response.
39 patterns:
40 - pattern: cors({ origin: $O, credentials: true })
41 - metavariable-pattern:
42 metavariable: $O
43 patterns:
44 - pattern-either:
45 - pattern: '"*"'
46 - pattern: true
47 - pattern: '(...) => true'
48 metadata:
49 cwe: 'CWE-942'SameSite=Lax (or Strict) and the __Host- prefix? (4) Are state-changing endpoints reachable via GET, and if so, why? (5) Is the JSON body parser strict about Content-Type, or does it accept text/plain? (6) Is CORS configured with explicit origins, never reflection-with-credentials? (7) Is the login endpoint itself CSRF-protected against login CSRF? (8) Are CSRF tokens compared in constant time? (9) Is the token masked or rotated per response to defeat BREACH? Any "no" is a finding.1// __tests__/csrf.spec.ts, characterisation tests that catch
2// regressions on every middleware change.
3import request from 'supertest';
4import { app } from '../src/app';
5
6describe('CSRF protection', () => {
7 let agent: request.SuperAgentTest;
8 beforeEach(async () => {
9 agent = request.agent(app);
10 await agent.post('/login').send({ user: 'alice', pw: 'pw' }).expect(200);
11 });
12
13 it('issues a __Host-csrf cookie on first request', async () => {
14 const r = await agent.get('/profile').expect(200);
15 expect(r.headers['set-cookie']?.some(c => c.startsWith('__Host-csrf='))).toBe(true);
16 });
17
18 it.each([
19 ['no token, no origin', {}, 403],
20 ['origin only, no token', { Origin: 'https://app.tld' }, 403],
21 ['bad origin', { Origin: 'https://evil.tld', 'X-CSRF-Token': 'x' }, 403],
22 ['mismatched token', { Origin: 'https://app.tld', 'X-CSRF-Token': 'wrong' }, 403],
23 ])('rejects POST with %s', async (_label, headers, status) => {
24 await agent.post('/transfer').set(headers).send({ to: 'x', amount: 1 }).expect(status);
25 });
26
27 it('accepts POST with matching token and trusted origin', async () => {
28 const cookies = (await agent.get('/profile')).headers['set-cookie'];
29 const token = /__Host-csrf=([^;]+)/.exec(cookies.join(';'))![1];
30 await agent
31 .post('/transfer')
32 .set('Origin', 'https://app.tld')
33 .set('X-CSRF-Token', token)
34 .send({ to: 'x', amount: 1 })
35 .expect(200);
36 });
37
38 it('rejects state-changing GET (defense against image-tag CSRF)', async () => {
39 await agent.get('/account/close?confirm=1').expect(405);
40 });
41
42 it('rejects text/plain body on JSON endpoint (defeats text/plain CSRF)', async () => {
43 await agent
44 .post('/api/role')
45 .set('Content-Type', 'text/plain')
46 .send('{"role":"admin"}')
47 .expect(415);
48 });
49});A code review finds 9 routes with `@csrf_exempt` in a Django project. The team lead says 'they are all webhooks from trusted vendors, so it is fine'. What is the right control?
07 //Real-World Case Studies
CSRF has a long CVE history, and the pattern is monotonous: a state-changing endpoint left unprotected, a researcher posts a one-page HTML proof-of-concept, the vendor ships a one-line fix. The interesting incidents are the ones where the bug appeared after a refactor that "should have been safe", a method-override middleware was added, a JSON parser was loosened, a route was moved from one app to another, a SameSite default was assumed but never set. These are the failures worth studying because they happen on teams that already knew about CSRF.
- Netflix CVE-2021-1370 (and similar pre-SameSite-default incidents), a state-changing endpoint reachable via GET. The OWASP rule "GET must be safe and idempotent" is not a style preference; in any application predating SameSite=Lax default, a single
<img>tag against a state-changing GET was a full CSRF. Many SaaS vendors had account-deletion-on-GET endpoints removed quietly between 2018 and 2021. - BREACH on Spring Security tokens (pre-XOR handler), before Spring Security shipped
XorCsrfTokenRequestAttributeHandlerin 5.8, CSRF tokens were reflected verbatim in HTML. Any endpoint that also reflected an attacker-controlled query string under gzip compression leaked the token byte by byte. Multiple internal apps at large enterprises were vulnerable; the fix is the masking handler, mandatory since 2023. - GitHub login CSRF (historical), GitHub patched a login CSRF in 2018 where an attacker could pre-stage a login flow so that a victim ended up authenticated as the attacker on the OAuth side, allowing the attacker to harvest data the victim later added. Login CSRF is the variant most often missed because it predates the user's "real" session.
- Drupal SA-CORE-2014-005 / Drupalgeddon-adjacent, while the famous Drupalgeddon was SQL injection, several adjacent CSRF bugs in the same period exploited the same pattern: form API tokens were not validated on certain admin endpoints, allowing a single <img> tag to enable maintenance mode, install modules, or escalate accounts.
- WordPress contact-form / membership plugins (long tail), dozens of CSRF advisories in plugins where developers ship "REST" endpoints without
check_ajax_referer. Every Patchstack quarterly report includes new entries. The fix is the same: WP's nonce API on every state-changing endpoint, no exceptions. - Express-based SPAs with body-parser type: "*/*" (2019-2024), multiple incident reports of JSON-CSRF via text/plain bodies against APIs that "could not possibly be CSRF'able because they only accept JSON". The lenient body-parser configuration was the root cause; the fix was a one-line config change plus an explicit Content-Type check.
- Same-site subdomain XSS into parent-domain CSRF (recurring), takeover of a forgotten subdomain (the perennial CNAME-pointing-at-dead-S3-bucket bug) gives the attacker JavaScript on a same-site origin. SameSite cookies do nothing; CSRF tokens are readable from the parent. Fix:
__Host-prefix on the session cookie, plus a subdomain takeover sweep as part of routine asset management.
Across the case studies, what is the recurring root cause?
08 //Beyond the Code: Auth Model, CORS, and the Cookie Future
The application-layer fix closes the injection. The architectural decisions, what does the auth model look like, how is CORS configured, what is the cookie strategy, decide whether a single CSRF regression escalates into an incident or stays a low-impact finding. The browser landscape is also shifting: third-party cookies are ending, Privacy Sandbox is changing what "cross-site" even means, and the Sec-Fetch-Site header is increasingly available as a primary signal. A 2026 CSRF defense looks different from a 2019 one.
Architectural Choices That Limit CSRF Blast Radius
| Choice | What it does | Why it limits CSRF impact |
|---|---|---|
| Re-authentication for sensitive actions | Require password or MFA before transfers, deletions, permission grants | A successful CSRF on /transfer hits a re-auth wall; the silent exploit does not complete |
| Per-action confirmation tokens | A signed, single-use token issued from a confirmation page; the action endpoint requires it | Cross-origin POSTs cannot mint the token because the confirmation page is protected by SameSite + CSRF |
| Sec-Fetch-Site as primary check | Reject any non-safe request whose Sec-Fetch-Site is cross-site or none | Browser-enforced, cheap, fails closed on browsers that send the header |
| __Host- prefix on all session and CSRF cookies | Browser refuses to overwrite from a subdomain; Path=/; Secure; no Domain | Subdomain takeover cannot poison parent cookies; SameSite loopholes shrink |
| Strict CORS allow-list | Allow-Origin is an explicit list of your own origins; never a reflection | A misconfigured CORS does not silently open every endpoint to credentialed cross-origin reads |
| Drop legacy plugin support | No Flash, no Java applet, no PDF-issued requests | Removes the legacy bypass paths that ignore SameSite and Origin |
| Short session + idle timeout on sensitive routes | Sensitive routes require a fresh session within N minutes | A CSRF that lands minutes after the user logged out fails because the session is gone |
1// lib/csrf-modern.ts, layered Sec-Fetch-Site + Origin + token.
2//
3// Sec-Fetch-Site is the cleanest CSRF signal a browser sends. We accept
4// "same-origin" and "same-site" on internal apps; we reject "cross-site"
5// and "none" on state-changing requests. The token + Origin checks remain
6// as fallback for browsers without Fetch Metadata (older Safari, weird
7// embedded webviews).
8
9import type { Request, Response, NextFunction } from 'express';
10
11const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
12const SAFE_FETCH_SITES = new Set(['same-origin', 'same-site', 'none']);
13const TRUSTED_ORIGINS = new Set([
14 'https://app.tld',
15 'https://www.app.tld',
16]);
17
18export function modernCsrf(req: Request, res: Response, next: NextFunction) {
19 if (SAFE_METHODS.has(req.method)) return next();
20
21 // Layer 1, Sec-Fetch-Site (preferred where available)
22 const fetchSite = req.get('sec-fetch-site');
23 if (fetchSite && !SAFE_FETCH_SITES.has(fetchSite)) {
24 return res.status(403).json({ error: 'cross-site request blocked' });
25 }
26 // "none" means a top-level navigation typed in the address bar; for
27 // sensitive POST endpoints, treat "none" as suspicious too:
28 if (fetchSite === 'none' && req.path.startsWith('/admin/')) {
29 return res.status(403).json({ error: 'direct navigation blocked' });
30 }
31
32 // Layer 2, Origin / Referer fallback
33 const origin = req.get('origin') ?? req.get('referer');
34 if (origin) {
35 try {
36 if (!TRUSTED_ORIGINS.has(new URL(origin).origin)) {
37 return res.status(403).json({ error: 'origin mismatch' });
38 }
39 } catch {
40 return res.status(403).json({ error: 'malformed origin' });
41 }
42 } else if (!fetchSite) {
43 // No Origin AND no Sec-Fetch-Site: a very old browser or a stripped
44 // request. Fail closed on state-changing endpoints.
45 return res.status(403).json({ error: 'missing origin signal' });
46 }
47
48 // Layer 3, token (synchronizer or signed double-submit)
49 // ... (verify token, constant-time compare; see earlier example)
50
51 next();
52}1// lib/route.ts, the only allowed way to register a state-changing
2// route. Direct app.post / app.put / app.delete is banned by lint.
3// Every registered route inherits CSRF + Origin + Sec-Fetch-Site checks.
4
5import type { Express, Request, Response, NextFunction } from 'express';
6import { modernCsrf } from './csrf-modern';
7
8type Handler = (req: Request, res: Response, next: NextFunction) => unknown;
9
10interface RouteOptions {
11 /** Set to "webhook" for HMAC-signed routes that legitimately bypass CSRF. */
12 auth?: 'session' | 'webhook' | 'bearer';
13 /** High-risk actions: require step-up auth before the handler runs. */
14 stepUp?: boolean;
15}
16
17export function mountWrite(
18 app: Express,
19 method: 'post' | 'put' | 'patch' | 'delete',
20 path: string,
21 handler: Handler,
22 opts: RouteOptions = { auth: 'session' },
23) {
24 const middlewares: Handler[] = [];
25
26 if (opts.auth === 'session') {
27 middlewares.push(modernCsrf);
28 } else if (opts.auth === 'webhook') {
29 middlewares.push(verifyHmacSignature); // implement per vendor
30 } else if (opts.auth === 'bearer') {
31 middlewares.push(verifyBearer); // implement per auth model
32 }
33
34 if (opts.stepUp) middlewares.push(requireRecentReauth);
35
36 app[method](path, ...middlewares, handler);
37}
38
39// Usage. The safe path is the only path; the unsafe path requires explicit opt-out.
40// mountWrite(app, 'post', '/transfer', transferHandler, { auth: 'session', stepUp: true });
41// mountWrite(app, 'post', '/webhooks/stripe', stripeHandler, { auth: 'webhook' });
42// mountWrite(app, 'delete', '/api/v1/users/:id', deleteHandler, { auth: 'bearer' });
43
44declare function verifyHmacSignature(req: Request, res: Response, next: NextFunction): void;
45declare function verifyBearer(req: Request, res: Response, next: NextFunction): void;
46declare function requireRecentReauth(req: Request, res: Response, next: NextFunction): void;09 //Conclusion
Cross-Site Request Forgery is a textbook case of ambient authority used against the user who holds it. The browser is correct; cookies are correct; HTML forms are correct. The vulnerability lives in the moment the application accepts a state-changing request and trusts the cookie without verifying the request was intended. Fix it the same way every adjacent class is fixed: one global middleware, applied at every sink, layered with browser-enforced controls (SameSite, Sec-Fetch-Site, __Host-) so that no single regression becomes an incident.
SameSite=Lax (or Strict) and the __Host- prefix · Validate Origin / Referer on every state-changing request; allow-list explicit origins · Treat Sec-Fetch-Site as a primary signal where available · Never mutate state on GET; enforce method discipline · Require strict Content-Type on JSON endpoints; reject text/plain · Configure CORS with explicit origins, never reflection-with-credentials · Protect the login endpoint against login CSRF · Mask or rotate tokens per render to defeat BREACH · Require re-authentication for high-value actions · Add a Semgrep / CodeQL rule that flags every CSRF opt-out.When you see a new state-changing endpoint in a diff, the first question is not "does the handler do the right thing", it is "does the global CSRF middleware reach this route, and is there any way to invoke this endpoint that bypasses it?". If the answer involves a method-override, a lenient body parser, a per-route exemption, or a missing Origin check, the bug class is alive. The fix is one middleware and one cookie attribute away. Pair this module with the CORS Misconfiguration, Session Fixation & Management, and Clickjacking & UI Redressing guides for the adjacent classes where the browser's default trust model is the attack surface.