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
| Control | Primary? | Stops | Gaps |
|---|---|---|---|
| Synchronizer token (session-bound, per session or per request) | Yes | cross-site + same-site forgery | must be enforced on every route/method/encoding; leaks via URL/XSS |
| Signed double-submit (HMAC over session-bound value + random) | Yes (stateless) | as above | unsigned/naive variant is cookie-injectable |
Custom request header (X-CSRF-Token, X-Requested-With) | Yes for XHR/API | anything that cannot preflight | only if server rejects absence and CORS allow-list is exact |
Sec-Fetch-Site policy + Origin fallback | Yes (OWASP, Go 1.25 CrossOriginProtection) | cross-site requests | same-site siblings unless same-site is rejected; needs fallback when headers absent |
| Origin/Referer exact match | Depth / pre-session | cross-origin requests | fail-open and substring bugs (Referer and Origin Validation Bypasses) |
SameSite=Lax/Strict | Depth | cross-site POST/subresource | GET mutations, siblings, grace window, Firefox/Safari defaults (SameSite Cookies) |
| Reject simple content types on JSON APIs | Depth | text/plain / form JSON CSRF | text/ping, query-param body channels (JSON CSRF) |
| Re-auth / OTP / CAPTCHA on critical actions | Depth | one-shot forgery | must 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-siteAdd 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
IHttpModulefor WebForms unmaintained since 2008, deserialized the CSRF form-field token with an unkeyedObjectStateFormatter(no MAC/signature) on every POST to aSystem.Web.UI.Page. A single unauthenticated POST with any non-empty CSRF cookie gave RCE inw3wp.exe; Mandiant observed in-the-wild exploitation and no patch exists. Replace it withSystem.Web.Helpers.AntiForgery,Page.ViewStateUserKeyplus MAC-verified/encrypted ViewState, or ASP.NET CoreIAntiforgery; huntWeb.configandbin/forAntiCsrfModule, review IIS logs for anomalous.aspxPOSTs returning 302/500 with largecs-bytes, and rotate<machineKey>and otherWeb.configsecrets 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.
Related
- Cross-Site Request Forgery
- SameSite Cookies
- CSRF Token Bypasses
- Referer and Origin Validation Bypasses
- JSON CSRF
- Login CSRF
- Method Override CSRF
- Session Management
Sources
- Cross-Site Request Forgery Prevention Cheat Sheet - OWASP · original
- Cross-site request forgery (CSRF) - Security - MDN Web Docs · original
- A Deep Dive into CSRF Protection in Rails – Ruby Inside – Medium · original
- How to protect Node.js apps from CSRF attacks · original
- WordPress Front End Security: CSRF and Nonces - CSS-Tricks · original
- Using CORS policies to implement CSRF protection - Mixmax · original
- Modern CSRF Mitigation in Single Page Applications · original
- Avoiding CSRF Attacks with API Design · original
- CSRF Protection - Clerk Docs · original
- Laravel Security: Prevent Mass Assignment, CSRF, and XSS · original
- ColdFusion Session Security: SameSite Cookies, CSRF Tokens, and Session Fixation Prevention · original
- ruby - Sinatra CSRF Authenticity tokens - Stack Overflow · original
- In Praise of CSRF Tokens – Tim MalcomVetter – Medium · original
- Wiping out CSRF · original
- Cross-Site Request Forgery is dead! · original
- Warpgate cross-site admin actions without origin check · original
- Hono csrf() does not check hyperlink auditing (text/ping) requests · original
- CVE-2026-44613: Turning a CSRF into Silent Unauthorized Actions · original
- coder: CSRF protection skipped for API paths matching unanchored exemption patterns · original
- Eight Doors, One Key: Chaining Misconfigurations into Full Account Takeover · original
- The CSRF Token Nobody Checked · original
- Thelia back-office CSRF token leak + GET deletes · original
- CVE-2026-122675: CSRF in Wp Social overwrites OAuth client credentials · original
- CSRF: The Bug Everyone Declared Dead and Nobody Actually Fixed · original
- CVE-2025-9611: Microsoft Playwright MCP Server CSRF Flaw · original
- Hackers Exploit Critical ASP.NET Anti-CSRF Library Flaw Allowing Unauthenticated RCE · original