CSRF Prevention

Layered controls that make the server able to tell an intended, same-origin, user-initiated state change from one the browser was induced to send: framework CSRF tokens or Fetch-Metadata/Origin enforcement as the primary control, with SameSite, safe-method discipline and non-simple requests as depth.

Control matrix

ControlPrimary?StopsGaps
Synchronizer token (session-bound, per session or per request)Yescross-site + same-site forgerymust be enforced on every route/method/encoding; leaks via URL/XSS
Signed double-submit (HMAC over session-bound value + random)Yes (stateless)as aboveunsigned/naive variant is cookie-injectable
Custom request header (X-CSRF-Token, X-Requested-With)Yes for XHR/APIanything that cannot preflightonly if server rejects absence and CORS allow-list is exact
Sec-Fetch-Site policy + Origin fallbackYes (OWASP, Go 1.25 CrossOriginProtection)cross-site requestssame-site siblings unless same-site is rejected; needs fallback when headers absent
Origin/Referer exact matchDepth / pre-sessioncross-origin requestsfail-open and substring bugs (Referer and Origin Validation Bypasses)
SameSite=Lax/StrictDepthcross-site POST/subresourceGET mutations, siblings, grace window, Firefox/Safari defaults (SameSite Cookies)
Reject simple content types on JSON APIsDepthtext/plain / form JSON CSRFtext/ping, query-param body channels (JSON CSRF)
Re-auth / OTP / CAPTCHA on critical actionsDepthone-shot forgerymust be single-use, server-verified

None of these address client-side CSRF (same-origin JS issuing attacker-steered requests): fix by not building request URLs/methods from attacker-controlled inputs (URL, fragment, window.name, postMessage, uploaded JSON), or by mapping inputs to a predefined set of safe requests.

Implementation patterns

Framework defaults (use, don’t reinvent): Rails protect_from_forgery with: :exception (per-form tokens since Rails 5; tokens masked with a one-time pad to blunt BREACH); Django {% csrf_token %} / X-CSRFToken; Laravel @csrf / X-CSRF-TOKEN / X-XSRF-TOKEN; Sinatra via Rack::Protection; WordPress nonces (wp_nonce_field, wp_verify_nonce, check_ajax_referer); ColdFusion sameSite on session/auth cookies plus tokens; Node: synchronizer token or signed double-submit (OWASP-referenced); Go 1.25 http.CrossOriginProtection.

Fetch Metadata policy (OWASP shape):

const site = req.get('Sec-Fetch-Site');            // same-origin | same-site | cross-site | none
if (!site) return originFallback(req);              // legacy clients: mandatory fallback
if (SAFE.has(req.method) || site === 'same-origin' || site === 'none') return next();
return res.status(403).end();                       // cross-site and (by default) same-site

Add Vary: Sec-Fetch-Site, Origin on responses that differ; explicitly allow-list intended cross-origin endpoints (webhooks, CORS APIs) and secure them separately.

Signed double-submit: HMAC-SHA-256 over length-prefixed session_id || random; token = random.hmac; read from header/body never cookie-only; constant-time compare; __Host- + Secure cookie.

SPA / API design: never mutate on GET; require JSON + custom header; exact CORS allow-list with credentials (no subdomain regex — a taken-over subdomain inherits it); or bearer tokens not held in cookies (no ambient credential).

Login/logout/registration: protect them too — pre-session tokens or Origin enforcement; login-form tokens also break credential-replay automation after phishing and surface password spraying as reused-token anomalies. See Login CSRF.

Local services: loopback HTTP APIs must validate Host and Origin (DNS rebinding) and require a secret — “localhost-only” is not authentication.

Common implementation failures

  • Enforcement only on POST or only on one content type → Method Override CSRF, JSON CSRF.
  • Exemption lists matched as unanchored regex (Coder), whole-prefix exclusions (Spring /legacy/**).
  • Token issued but never compared (Messenger.com 2015), compared to a global pool, or in URLs (Thelia).
  • CSRF middleware only inspecting form content types (Hono text/ping).
  • Per-handler checks forgotten on one branch (Wp Social provider settings lacked the nonce check every sibling handler had; emlog ai.php; WordPress plugins missing nonces).
  • Wildcard CORS with credentials by default (Zeppelin allowed.origins=*).
  • The CSRF library as attack surface: Idunno.AntiCsrf 0.9.1.0 / 0.9.1 Beta (CVE-2026-131914, CVSS 9.3), a double-submit IHttpModule for WebForms unmaintained since 2008, deserialized the CSRF form-field token with an unkeyed ObjectStateFormatter (no MAC/signature) on every POST to a System.Web.UI.Page. A single unauthenticated POST with any non-empty CSRF cookie gave RCE in w3wp.exe; Mandiant observed in-the-wild exploitation and no patch exists. Replace it with System.Web.Helpers.AntiForgery, Page.ViewStateUserKey plus MAC-verified/encrypted ViewState, or ASP.NET Core IAntiforgery; hunt Web.config and bin/ for AntiCsrfModule, review IIS logs for anomalous .aspx POSTs returning 302/500 with large cs-bytes, and rotate <machineKey> and other Web.config secrets on evidence of compromise (The Hacker News). A CSRF token must be an opaque, MAC-verified value, never a serialized object. See Insecure Deserialization.
  • See CSRF Token Bypasses.

Sources