OOmnistu

Blog / Security

Security

CSRF prevention basics: tokens, double-submit cookies and Fetch Metadata

Review CSRF tokens, cookie settings, origin checks and Fetch Metadata for requests that carry browser credentials automatically.

OOmnistu
Reviewed 2026-11-16 · 6 min read

At a glance

  • Use your framework's built-in CSRF protection first; otherwise add server-validated tokens to every state-changing request.
  • Tokens remain essential for apps using cookie authentication.
  • SameSite helps but is not sufficient alone: a state-changing GET defeats Lax - the sheet's most common failure.
  • XSS can defeat all CSRF defences - fix XSS too.

Cross-site request forgery (CSRF) happens when a malicious site, email or message tricks a logged-in user's browser into making an unwanted request to a site they trust. Browsers can send cookies, including session cookies, automatically, so an unprotected site cannot tell a forged request from a real one. This article summarises OWASP's CSRF Prevention Cheat Sheet, read on 15 November 2026, except the detailed Origin/Referer matching steps and the JavaScript snippet for adding tokens to AJAX requests. It is one source's guidance, not a certification.

What an attacker can do

Only what the app exposes and the user is allowed to do: the sheet lists transferring funds, changing a password, making a purchase or elevating privileges. It stresses that cross-site scripting (XSS) can defeat all CSRF defences, so fix XSS too. Tokens remain essential for apps using cookie authentication.

The sheet's order of preference

  1. Use your framework's built-in CSRF protection if it has one. The sheet names .NET's built-in tokens and Go's CrossOriginProtection type (from Go 1.25, Fetch-Metadata based).
  2. Otherwise add CSRF tokens to all state-changing requests and validate them on the server.
  3. Modern-browser-only software can use Fetch Metadata headers with a fallback.
  4. Stateful apps: the synchronizer token pattern. Stateless apps: double-submit cookies. API sites that cannot use form tags: custom request headers.
  5. Add at least one defence-in-depth measure. The sheet lists SameSite cookies (but do not set a cookie for a whole domain, since subdomains then share it), user-interaction checks for very sensitive actions, and origin verification with standard headers.
  6. Never use GET for state-changing operations.

Synchronizer token pattern

The server generates a token that is unique per user session, secret and unpredictable (large random value from a secure source), keeps it in the session, and checks every state-changing request against it. Reject and log requests with a missing or mismatched token. Per-request tokens shrink the window for a stolen token but can break the Back button, producing false alarms. Send the token in the response body and return it as a hidden form field, header or JSON value. Do not put it in a cookie (for this pattern), the URL or the logs. A custom header set by JavaScript is more secure than a hidden field because custom headers fall under the same-origin policy.

Double-submit cookies

For stateless apps. The sheet recommends the signed version, tying the token to the authenticated session with an HMAC (HMAC-SHA-256 over a session-dependent value and a random value, with a server-side secret key), setting the cookie Secure, and reading the token from a header or form field, never from the cookie alone. Avoid static values such as the user's email or ID. It says adding timestamps for expiry is a misconception: a CSRF token is not an access token, and a new session should get a new token. The naive version, comparing a random cookie to a request value, is discouraged: an attacker who can write cookies on your domain (for example through a vulnerable sibling subdomain or DNS takeover) can bypass it.

Fetch Metadata headers

Browsers send Sec-Fetch-Site, which says whether a request is same-origin, same-site, cross-site or none. The sheet's suggested policy for state-changing methods:

The sheet says all major browsers have sent these headers since March 2023 and requires a fallback for older ones. The app must be served over HTTPS, since the headers are only sent to trustworthy URLs, and safe methods must not change state.

Rollout and gaps for Fetch Metadata

Start in log-only mode and review what would be blocked before enforcing. Monitor which browsers send the headers, and keep a documented list of cross-origin exceptions. Add Vary: Sec-Fetch-Site, Origin when responses differ by those headers, so caches do not reuse the wrong response; the sheet says this is operational, not a defence. It warns that proxies and gateways may strip Origin and Sec-* headers, and that prefetch and prerender flows can send headers that do not match the final navigation.

Simple requests, headers and content types

Browsers send form posts as "simple" requests that are not preflighted and may go to any origin. A JSON API that also accepts text/plain or form content types can therefore be exposed; the sheet suggests rejecting those simple content types. For AJAX and API calls, a custom header such as X-CSRF-Token is a user-friendly option, since cross-origin custom headers need a CORS preflight. The sheet still advises tokens as an extra layer in case of a browser bug.

SameSite: useful, not sufficient alone

Strict

No cookies on cross-site requests, even link clicks.

Lax

Cookies sent on top-level safe-method navigations. A state-changing GET still defeats it.

None

Requires Secure. Needed for genuine cross-site use.

Values: Strict (no cookies on cross-site requests, even link clicks), Lax (cookies sent on top-level safe-method navigations) and None (requires Secure). The sheet lists limits:

It says SameSite can suffice alone only in narrow cases: no shared registrable domain with untrusted hosts, no state change via safe methods, a Strict cookie (or Lax with the __Host- prefix and an audit of every GET handler), origin verification, and acceptance of users whose browsers ignore it. Otherwise combine it with tokens.

Origin and user-interaction defences

Compare the complete parsed Origin (or Referer origin if Origin is absent) against the trusted target origin, not a substring or suffix. Reject protected requests with missing or null origins unless another configured CSRF defense succeeds. Trust forwarded target-host headers only from correctly configured trusted proxies; these are browser-set headers that scripts cannot change. The sheet notes HTTPS alone does not guarantee Origin is present. For critical actions such as password changes or money transfers, re-authentication or one-time tokens give strong protection at a usability cost. Do not use CAPTCHA for this: it proves human presence, which can be obtained from another session.

Client-side CSRF and login forms

Client-side CSRF happens when your own JavaScript builds requests from attacker-controllable input such as the URL, window.name, referrer or postMessage. It can bypass tokens and SameSite because the request is genuinely from your page. Mitigations named: keep request generation independent of such inputs, validate strictly, or use a fixed list of safe request data. Login forms can also be targeted: an attacker logs the victim into the attacker's account, then the victim may enter card details there. Use a pre-session token on the login form, and replace the pre-session with a new session after login to avoid fixation.

Limits

We did not read the step-by-step Origin/Referer matching rules, the cookie host-prefix detail or the AJAX token snippet. We quote no incident figures. See our cookies, CORS and session articles.

By Omnistu.

Sources

Previous
Time to First Byte (TTFB): how to measure a slow server response and what can reduce it