LeepCast
Subscribe
All posts
Security

CSRF Protection Explained: SameSite Cookies, Fetch Metadata, and When You Still Need Tokens

Cross-site request forgery still works against cookie-authenticated apps that rely on a single defense. Learn how SameSite, Sec-Fetch-Site, Origin checks, and signed tokens each work, where each fails, and how to layer them.

LeepCast7 min read

Cross-site request forgery is an old bug with a simple core idea. A browser attaches cookies to requests based on where the request is going, not on which page started it. If a user is signed in to a banking app and then visits a hostile page, that page can submit a form to the bank, and the browser will happily include the session cookie. The bank sees a valid session and performs the action. No password was stolen and no code ran on the bank's domain; the attacker simply borrowed the user's browser.

The defenses have changed a lot in the last few years. SameSite cookies are now widely enforced, every major browser sends Fetch Metadata headers, and Go 1.25 shipped a CSRF guard in its standard library that relies on those headers instead of tokens. That leaves many teams unsure which layer actually matters. This guide explains how each defense works, where each one quietly fails, and how to combine them into a small policy you can reason about, with a runnable Python example.

What an attack needs to succeed

A forged request only works when three conditions line up. Looking at them separately makes it obvious why each defense targets a different one.

  1. Ambient credentials: the server authenticates the request using something the browser sends automatically, which in practice is almost always a session cookie.
  2. A predictable request: the attacker can construct every parameter the action needs, such as the amount and destination account, without knowing any secret.
  3. No origin check: the server never asks where the request came from before acting on it.

APIs that authenticate with a bearer token placed in an Authorization header by JavaScript are not exposed to classic CSRF, because a hostile page cannot make the browser add that header for it. The risk is concentrated in cookie-authenticated apps, which still describes most server-rendered sites and many single-page apps that use session cookies for convenience.

Layer 1: SameSite cookies

The SameSite attribute tells the browser whether to send a cookie on requests that cross a site boundary. Strict never sends it cross-site, even when a user clicks a link from another site into yours, which means users arrive looking logged out. Lax sends the cookie on top-level navigations with safe methods like a clicked link, but withholds it from cross-site form POSTs, fetch calls, and embedded resources. None sends it everywhere and must be paired with Secure.

Lax blocks the textbook hidden-form attack, so it is tempting to stop there. The OWASP CSRF cheat sheet lists the gaps that make that unwise:

  • Any GET handler that changes state is still reachable, because Lax allows cookies on cross-site GET navigations. A logout link, an unsubscribe URL, or a legacy /delete? id= endpoint is enough.
  • Same-site is not same-origin. A site is roughly the registrable domain, so a request from forum. example. com to app. example. com counts as same-site and carries the cookie. A subdomain takeover or a host serving user content becomes a launch point.
  • Defaults differ. Chromium treats cookies without the attribute as Lax, while other engines do not, so an omitted attribute gives uneven protection. Always set it explicitly.
  • It does nothing against client-side CSRF, where your own JavaScript is tricked into sending a request with attacker-chosen parameters.

A useful companion is the __Host- cookie prefix. MDN documents that browsers only accept such a cookie when it is Secure, has Path=/, and has no Domain attribute, which locks it to the exact host that set it. Naming the session cookie __Host-session stops sibling subdomains from planting or overwriting it.

Layer 2: Fetch Metadata and the Origin header

Modern browsers attach a Sec-Fetch-Site header to every request sent to an HTTPS origin. Its value is same-origin, same-site, cross-site, or none, where none means the user started the request directly, for example by typing the URL or opening a bookmark. Scripts cannot forge or remove it, because names beginning with Sec- are forbidden headers. Support arrived in Safari 16.4 in 2023, which completed coverage across the major engines.

That makes a resource isolation policy only a few lines long: if the method is not safe and Sec-Fetch-Site is cross-site, reject the request. Go 1.25's http. CrossOriginProtection does essentially this, and falls back to comparing the Origin header's host with the Host header when Sec-Fetch-Site is missing. Its documentation is also explicit that requests carrying neither header are allowed, on the assumption that they come from non-browser clients or same-origin contexts.

For older clients, the Origin header is the fallback signal. Compare it with an origin you configure on the server rather than one derived from the request, since a reverse proxy can rewrite Host. Match the whole origin string, so that app. example. com. attacker. net cannot slip past a prefix check, and treat the literal value null as untrusted.

Layer 3: tokens, done the modern way

A CSRF token is a secret value that the server expects back in a form field or custom header on every state-changing request. A hostile page cannot read your pages, so it cannot learn the value. The classic synchronizer token pattern stores one per session on the server. If you prefer to keep state out of the server, OWASP now recommends a signed double-submit token: an HMAC over a session-bound value plus a random nonce, verified with a constant-time comparison. The older naive double-submit pattern, which only checks that a cookie and a form field match, is discouraged because anyone who can write a cookie on your domain can make the two match.

Tokens remain the layer that holds when the others are weakened: when a proxy strips Sec-Fetch headers, when a sibling subdomain is compromised, or when an old browser ignores SameSite. If your framework already provides them, as Django, Rails, Laravel, and . NET do, keep them switched on rather than writing your own.

A worked example: one policy, three layers

The script below combines the checks into a single allow function. Safe methods pass, because they must never change state. Cross-site unsafe requests are rejected from Fetch Metadata alone. If Sec-Fetch-Site is absent, a foreign or null Origin is rejected. Everything that survives must still present a valid session-bound HMAC token. It needs Python 3.10 or newer and only the standard library, and it ends with a table of test cases.

python
import hashlib
import hmac
import secrets

SECRET = secrets.token_bytes(32)  # load from a secret store in production
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
TRUSTED_ORIGIN = "https://app.example.com"


def _mac(session_id: str, nonce: str) -> bytes:
    # Length-prefixed so ("ab", "c") and ("a", "bc") never collide.
    msg = f"{len(session_id)}:{session_id}|{len(nonce)}:{nonce}".encode()
    return hmac.new(SECRET, msg, hashlib.sha256).digest()


def issue_token(session_id: str) -> str:
    nonce = secrets.token_hex(16)
    return f"{nonce}.{_mac(session_id, nonce).hex()}"


def token_valid(session_id: str, token: str | None) -> bool:
    if not token or token.count(".") != 1:
        return False
    nonce, mac_hex = token.split(".")
    if len(nonce) != 32 or len(mac_hex) != 64:
        return False
    try:
        bytes.fromhex(nonce)
        submitted = bytes.fromhex(mac_hex)
    except ValueError:
        return False
    return hmac.compare_digest(submitted, _mac(session_id, nonce))


def allow(method: str, headers: dict, session_id: str, token: str | None) -> bool:
    """headers uses lowercase names; token comes from a header or form field."""
    if method in SAFE_METHODS:
        return True  # safe methods must never change state
    site = headers.get("sec-fetch-site")
    if site == "cross-site":
        return False
    if site is None:  # older browser or non-browser client
        origin = headers.get("origin")
        if origin is not None and origin != TRUSTED_ORIGIN:
            return False
    return token_valid(session_id, token)


sid = "sess-7f3a"
tok = issue_token(sid)
cases = [
    ("POST", {"sec-fetch-site": "same-origin"}, sid, tok, True),
    ("POST", {"sec-fetch-site": "cross-site"}, sid, tok, False),
    ("POST", {"sec-fetch-site": "same-origin"}, sid, None, False),
    ("POST", {"sec-fetch-site": "same-origin"}, "sess-other", tok, False),
    ("POST", {"origin": "https://evil.example"}, sid, tok, False),
    ("POST", {"origin": "null"}, sid, tok, False),
    ("POST", {"origin": "https://app.example.com"}, sid, tok, True),
    ("GET", {"sec-fetch-site": "cross-site"}, sid, None, True),
]
for method, headers, s, t, expected in cases:
    assert allow(method, headers, s, t) == expected, (method, headers, s)
print(f"all {len(cases)} cases behave as expected")

Notice the fourth test case. The token was issued for one session and replayed with another, and it fails because the HMAC covers the session identifier. That binding is what separates the signed pattern from the naive one. In a real app the session identifier must be the server-side value, never something the client sends, and the secret must come from your key management system rather than being regenerated at startup as it is in this demo.

Common mistakes

  • Letting GET change state. Every layer above assumes safe methods are read-only, so a state-changing GET defeats SameSite=Lax, Fetch Metadata policies, and Go's built-in guard at once.
  • Exempting JSON endpoints. An endpoint that accepts text/plain or form encodings and parses the body as JSON anyway can be hit by a plain cross-site form. Reject unexpected content types.
  • Comparing tokens with ==. Use a constant-time function such as hmac. compare_digest.
  • Putting tokens in URLs. Query strings end up in logs, browser history, and Referer headers.
  • Setting Domain=example. com on the session cookie. It widens the cookie to every subdomain, including ones you may not control later.
  • Forgetting the login form. Login CSRF can sign a victim into the attacker's account, so pre-session forms need an Origin check or a pre-session token.

A decision checklist

  • Does the app authenticate with cookies? If not, classic CSRF largely does not apply, but check any cookie-based fallback paths.
  • Does your framework ship CSRF protection? Enable it and confirm it covers every unsafe method.
  • Are all state changes behind POST, PUT, PATCH, or DELETE? Audit GET handlers before trusting any other layer.
  • Is the session cookie named with __Host- and set with SameSite=Lax or Strict, Secure, and HttpOnly?
  • Do you reject unsafe requests with Sec-Fetch-Site: cross-site, with an Origin check as fallback?
  • Do your proxies, CDNs, and load balancers forward Sec-Fetch-* and Origin unchanged? Test this in staging.
  • Do intentional cross-origin endpoints such as webhooks or partner APIs have explicit exemptions with their own authentication?

When Fetch Metadata alone is enough, and when it is not

For a modern app on a single host that does not share its registrable domain with anything you do not control, has no state-changing GETs, and serves users on current browsers, a Fetch Metadata policy with an Origin fallback is a reasonable primary defense. Go's standard library makes that bet. Keep tokens when you must support very old or embedded browsers, when traffic passes through infrastructure that may drop headers, when you trust sibling subdomains less than your own origin, or when an action is valuable enough that a second, independent check is worth a few lines of code. For the highest-risk actions, such as changing an email address or moving money, add re-authentication or a one-time code, since no request-level check can confirm that the user actually intended the action.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments