# 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):** ```js 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=*`). - 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 - [[raw/cheatsheetseries.owasp.org/cross-site-request-forgery-prevention-cheat-sheet-owasp-2877|Cross-Site Request Forgery Prevention Cheat Sheet - OWASP]] - [[raw/developer.mozilla.org/cross-site-request-forgery-csrf-security-mdn-web-docs-2991|Cross-site request forgery (CSRF) - Security - MDN Web Docs]] - [[raw/medium.com/a-deep-dive-into-csrf-protection-in-rails-ruby-inside-medium-957|A Deep Dive into CSRF Protection in Rails – Ruby Inside – Medium]] - [[raw/snyk.io/how-to-protect-node-js-apps-from-csrf-attacks-9782|How to protect Node.js apps from CSRF attacks]] - [[raw/css-tricks.com/wordpress-front-end-security-csrf-and-nonces-css-tricks-936|WordPress Front End Security: CSRF and Nonces - CSS-Tricks]] - [[raw/mixmax.com/using-cors-policies-to-implement-csrf-protection-mixmax-932|Using CORS policies to implement CSRF protection - Mixmax]] - [[raw/medium.com/modern-csrf-mitigation-in-single-page-applications-4249|Modern CSRF Mitigation in Single Page Applications]] - [[raw/thedreaming.org/avoiding-csrf-attacks-with-api-design-2241|Avoiding CSRF Attacks with API Design]] - [[raw/clerk.com/csrf-protection-clerk-docs-3423|CSRF Protection - Clerk Docs]] - [[raw/medium.com/laravel-security-prevent-mass-assignment-csrf-and-xss-14488|Laravel Security: Prevent Mass Assignment, CSRF, and XSS]] - [[raw/medium.com/coldfusion-session-security-samesite-cookies-csrf-tokens-and-session-f-12489|ColdFusion Session Security: SameSite Cookies, CSRF Tokens, and Session Fixation Prevention]] - [[raw/stackoverflow.com/ruby-sinatra-csrf-authenticity-tokens-stack-overflow-937|ruby - Sinatra CSRF Authenticity tokens - Stack Overflow]] - [[raw/medium.com/in-praise-of-csrf-tokens-tim-malcomvetter-medium-928|In Praise of CSRF Tokens – Tim MalcomVetter – Medium]] - [[raw/medium.com/wiping-out-csrf-929|Wiping out CSRF]] - [[raw/scotthelme.co.uk/cross-site-request-forgery-is-dead-933|Cross-Site Request Forgery is dead!]] - [[raw/github.com/warpgate-cross-site-admin-actions-without-origin-check-13245|Warpgate cross-site admin actions without origin check]] - [[raw/github.com/hono-csrf-does-not-check-hyperlink-auditing-text-ping-requests-14385|Hono csrf() does not check hyperlink auditing (text/ping) requests]] - [[raw/ox.security/cve-2026-44613-turning-a-csrf-into-silent-unauthorized-actions-11104|CVE-2026-44613: Turning a CSRF into Silent Unauthorized Actions]] - [[raw/github.com/coder-csrf-protection-skipped-for-api-paths-matching-unanchored-exempt-13924|coder: CSRF protection skipped for API paths matching unanchored exemption patterns]] - [[raw/medium.com/eight-doors-one-key-chaining-misconfigurations-into-full-account-takeo-12490|Eight Doors, One Key: Chaining Misconfigurations into Full Account Takeover]] - [[raw/masimshahzad.medium.com/the-csrf-token-nobody-checked-14075|The CSRF Token Nobody Checked]] - [[raw/github.com/thelia-back-office-csrf-token-leak-get-deletes-13244|Thelia back-office CSRF token leak + GET deletes]] - [[raw/mor-golan.github.io/cve-2026-122675-csrf-in-wp-social-overwrites-oauth-client-credentials-15676|CVE-2026-122675: CSRF in Wp Social overwrites OAuth client credentials]] - [[raw/medium.com/csrf-the-bug-everyone-declared-dead-and-nobody-actually-fixed-13022|CSRF: The Bug Everyone Declared Dead and Nobody Actually Fixed]] - [[raw/sentinelone.com/cve-2025-9611-microsoft-playwright-mcp-server-csrf-flaw-4652|CVE-2025-9611: Microsoft Playwright MCP Server CSRF Flaw]]