Attacks & threats

9 min readUpdated

What is CSRF (cross-site request forgery) and how do you prevent it?

Quick answer

Cross-site request forgery (CSRF) is an attack in which a malicious page makes a victim's browser send a state-changing request to a site where the victim is signed in, such as changing an email address or making a transfer. The browser attaches the session cookie automatically, so the request looks genuine. The defence is to reject requests that did not come from your own pages: CSRF tokens, Fetch Metadata or Origin checks, and explicit SameSite cookies.

01What is CSRF?

CSRF abuses the fact that browsers attach cookies to a request based on where it goes, not on which page started it. If you are signed in to a site and open a malicious page in another tab, that page can make your browser send a request to the site, and the browser may include your session cookie. Unless the server checks where the request came from, it cannot tell it from one you made yourself.

The attacker never sees the response or your password. What they get is one action performed with your privileges; OWASP's examples include transferring funds, changing a password, making a purchase and elevating privileges. Changing the account's email address can be enough, because the next password reset then goes to the attacker.

CSRF had its own OWASP Top 10 entry until 2017, when it was dropped because, in OWASP's words, many frameworks include defences and it was found in only 5% of applications. It has not gone away: the OWASP Top 10:2025 lists it (CWE-352) under A01 Broken Access Control.

02How does a CSRF attack work?

A classic attack needs three conditions: the victim has a session on the target site, the session is carried by a cookie the browser sends automatically, and the action can be triggered by a request whose parameters the attacker can predict. A transfer form that needs only an amount and an account number qualifies; one that also asks for the current password does not.

Two variants matter in practice. Login CSRF signs the victim into the attacker's account, so whatever they enter next, such as card details, lands with the attacker. Client-side CSRF tricks the site's own JavaScript into sending a request built from attacker-controlled input, which comes from the same origin and passes every cross-site check. Any cross-site scripting bug defeats all CSRF defences.

  • The victim signs in to the target site, and the browser stores the session cookie
  • Later the victim opens a page the attacker controls, or an email or advert that loads one
  • That page submits a hidden form to the target, or loads a URL that changes state with GET
  • The browser sends the request with the victim's cookies, and the server performs the action
Request headerFrom your own formForged from another site
CookieThe victim's session cookieThe same cookie, if the browser attaches it
Originhttps://example.comhttps://attacker.example, or null
Sec-Fetch-Sitesame-origincross-site
RefererA page on example.com, when sentThe attacker's page, or absent
CSRF tokenPresent and matching the sessionMissing or wrong

03Does SameSite stop CSRF? Browser defaults compared

The SameSite cookie attribute tells the browser when to send a cookie on cross-site requests. Strict never sends it cross-site. Lax sends it only on top-level navigations with a safe method such as GET, so a cross-site form POST arrives without it. None always sends it and requires Secure. A session cookie with an explicit SameSite=Lax or Strict blocks the classic form-POST attack in every current browser.

The catch is the default for cookies that omit the attribute. Many guides say every modern browser treats them as Lax; only Chromium-based browsers do. Mozilla enabled Lax by default in Firefox Beta 96 in December 2021, withdrew it after site breakage and closed the effort as WONTFIX in November 2023; in November 2024 a Mozilla engineer confirmed that Firefox uses None when the attribute is missing. MDN's compatibility data lists no Lax default for Safari either.

The cookie specification draft (RFC 6265bis) treats a missing attribute like Lax and permits Chromium's compromise, which Google called temporary in 2019 and MDN still documents: a cookie without SameSite that is at most two minutes old is still sent on a top-level cross-site POST.

BrowserCookie without SameSite behaves asNotes
Chrome 80 and laterLaxRolled out February to August 2020; two-minute Lax+POST exception
Edge 86 and later, Opera 71 and laterLaxSame Chromium behaviour
Chrome on iOSNot changed to LaxGoogle's announcement excluded it from the change
FirefoxNoneLax only with the network.cookie.sameSite.laxByDefault preference
SafariNoneNo Lax default in MDN's compatibility data

04How do you prevent CSRF? The defences compared

Use the framework's built-in protection first: Django, ASP.NET Core and, since version 1.25, Go's standard library ship one, and OWASP recommends them over home-made code. OWASP also advises against relying on a CAPTCHA, which proves a human is present but not that this user meant this request.

DefenceHow it worksStrengthWeak spots
Synchroniser tokenThe server keeps a random token in the session, embeds it in every form and rejects requests without itStrong, in every browserEvery form and AJAX call must carry it; per-request tokens break the back button
Signed double-submit cookieThe token travels in a cookie and in the request, bound to the session with an HMAC, so no server state is neededStrong when bound to the sessionThe naive unsigned version fails when an attacker can write cookies, for example from a sibling subdomain
Fetch Metadata checkThe browser states whether the request came from the same origin, the same site or elsewhere; cross-site writes are rejectedStrong in current browsers, no tokensNeeds HTTPS and a fallback for browsers without the header
Origin or Referer checkCompare the Origin header with your own public originGood fallbackOrigin can be absent or null; behind a proxy you must know the public origin
SameSite=Lax or StrictThe browser withholds the cookie on cross-site POSTsGood defence in depthOnly a default in Chromium; misses state-changing GETs and sibling subdomains
Re-authentication or one-time codeThe user confirms sensitive actionsStrongest for critical actionsFriction; keep it for password, email and payment changes

05How do I check Sec-Fetch-Site and Origin on the server?

Fetch Metadata is the easiest defence to add to an existing application, because forms do not change. Browsers send Sec-Fetch-Site to HTTPS origins (Chrome since version 76, Firefox since 90, Safari since 16.4) with one of four values: same-origin, same-site, cross-site, or none for typed addresses and bookmarks. Go 1.25 built the check into its standard library as CrossOriginProtection; the middleware below follows the same rules in plain Node.js.

The rules: let safe methods through, because they must never change state; allow origins you list; if Sec-Fetch-Site is present, accept only same-origin and none; otherwise compare Origin with the Host header. Like Go's version, it allows requests with neither header, assuming they are same-origin or not from a browser. Treat same-site as untrusted unless you trust every subdomain, and behind a reverse proxy make sure the application sees the public Host header.

Fetch Metadata check with an Origin fallback
const http = require("node:http");

const SAFE = new Set(["GET", "HEAD", "OPTIONS"]);
const TRUSTED = new Set(["https://example.com"]); // origins allowed to post here

function isCrossOriginWrite(req) {
  if (SAFE.has(req.method)) return false;            // safe methods must not change state
  const origin = req.headers["origin"];
  if (origin && TRUSTED.has(origin)) return false;
  const site = req.headers["sec-fetch-site"];        // sent by current browsers
  if (site) return site !== "same-origin" && site !== "none";
  if (!origin) return false;                         // no browser signal at all
  try {
    return new URL(origin).host !== req.headers["host"]; // fallback for older browsers
  } catch {
    return true;                                     // "Origin: null" or garbage
  }
}

http.createServer((req, res) => {
  if (isCrossOriginWrite(req)) {
    res.writeHead(403, { "Content-Type": "text/plain" });
    return res.end("cross-origin request rejected\n");
  }
  res.end("ok\n");
}).listen(8080, "127.0.0.1");

// tested: POST cross-site 403, POST same-site 403, POST same-origin 200, POST none 200,
// GET cross-site 200, POST Origin: https://evil.example 403, POST Origin: null 403,
// POST Origin matching Host 200, POST from a listed origin 200, POST without browser headers 200

06Can a WAF stop CSRF?

Partly. A web application firewall or reverse proxy sees the same headers the application does, so it can enforce the coarse rule at the edge: refuse POST, PUT, PATCH and DELETE requests a browser labels cross-site. That works as an extra layer, or as a stopgap for an unprotected application, a form of virtual patching. Exempt legitimate cross-site POSTs first, such as payment callbacks and single sign-on responses.

What it cannot do is judge intent. A forged request carries the victim's real session cookie, a normal browser and well-formed parameters; nothing in it matches an attack signature, and the edge does not know your session state, so it cannot validate a synchroniser token.

  • Can: reject state-changing requests the browser marks as cross-site, for every application behind it
  • Can: shield a known state-changing GET from cross-site calls while the code is fixed
  • Cannot: validate CSRF tokens, or tell a forged request from a genuine one by its content
  • Cannot: stop client-side CSRF or requests from injected script, which share your origin
Edge rule: reject cross-site writes (passes nginx -t, nginx 1.22.1)
# http context
map "$request_method:$http_sec_fetch_site" $csrf_block {
    default                                              0;
    "~^(POST|PUT|PATCH|DELETE):(cross-site|same-site)$"  1;
}

server {
    location /account/ {
        if ($csrf_block) { return 403; }
        proxy_pass http://127.0.0.1:8080;
    }
}

07How do I test a site for CSRF?

Test your own application, or one you are authorised to test, by replaying a state-changing request with its evidence of origin removed or changed. If the server still performs the action, the endpoint is unprotected. A rejection usually comes back as a 403 Forbidden; Django, for example, answers "CSRF verification failed. Request aborted." and logs a reason such as an origin missing from its trusted origins.

  • Send the request without the CSRF token, and with a token from another session: both must fail
  • Send it with Sec-Fetch-Site: cross-site, and with Origin set to another site: both must fail
  • Check every GET endpoint for side effects, which Lax cookies and Fetch Metadata rules let through by design
  • Include the login form and the logout link, which are often left out
Replaying a request as a forged cross-site one (your own application only)
curl -s -o /dev/null -w '%{http_code}\n' -X POST https://app.example.com/account/email \
  -H 'Cookie: session=YOUR_TEST_SESSION' -H 'Sec-Fetch-Site: cross-site' \
  -H 'Origin: https://attacker.example' --data 'email=test@example.org'
# expected: 403

08CSRF and its defences: a dated timeline

Browser defaults changed several times, which is why advice written in different years disagrees.

DateChange
2013CSRF is A8 in the OWASP Top 10
2017Dropped from the OWASP Top 10, found in 5% of applications
February 2020Chrome 80 begins rolling out SameSite=Lax by default
April 2020Google temporarily rolls the enforcement back because of COVID-19
July to August 2020Rollout resumes with Chrome 84 on 14 July; all Chrome 80+ users targeted from 11 August
December 2021Firefox enables Lax by default in Beta 96 and Nightly 97
March 2022Mozilla restricts it to early beta again after site breakage
March 2023Safari 16.4 adds Fetch Metadata; all major browsers now send Sec-Fetch-Site
November 2023Mozilla closes its Lax-by-default effort as WONTFIX
August 2025Go 1.25 adds CrossOriginProtection, a token-free defence
2025OWASP Top 10:2025 keeps CSRF (CWE-352) under A01 Broken Access Control

Questions

Frequently asked questions

01What is the difference between CSRF and XSS?
Cross-site scripting injects script into your site, so the attacker's code runs as your page and can read data and send any request. CSRF runs nothing on your site: it makes the victim's browser send one request from another site, without seeing the response. XSS is the more powerful bug, and it defeats every CSRF defence, because requests from injected script are same-origin and can read the tokens.
02Is SameSite=Lax enough to prevent CSRF?
On its own, rarely. It blocks the classic cross-site form POST, but only where you set it explicitly, since Firefox and Safari do not apply Lax by default. It still allows cross-site GET navigations, so any GET that changes state stays exposed, and it treats sibling subdomains as the same site. OWASP describes it as a defence-in-depth layer to combine with tokens or Fetch Metadata checks.
03What is a CSRF token?
A CSRF token is a secret, unpredictable value that the server ties to the user's session and places in each form or page. The browser sends it back with the request in a form field or header, and the server rejects requests where it is missing or wrong. A page on another site cannot read your pages, so it cannot learn the token, which is what makes a forged request fail.
04Do I need CSRF protection for a JSON API?
It depends on how the API authenticates. If it relies on cookies, yes, because a page on another site can send simple requests, including form-encoded POSTs, that may carry those cookies. If every call needs an Authorization header with a token that your own scripts add, a forged request from another site cannot include it, so classic CSRF does not apply. Reject unexpected content types either way.

Sources

Sources and verification

Checked on 13 November 2026 on Debian 12: the nginx configuration in “Can a WAF stop CSRF?” passes nginx -t (nginx 1.22.1). Other configuration, commands, log lines and output on this page are examples: adapt them to your system and check them before use.

  1. 01Cross-Site Request Forgery Prevention Cheat Sheet · OWASP
  2. 02Set-Cookie: SameSite values and browser compatibility (Defaults to Lax) · MDN
  3. 03SameSite Updates: Lax-by-default launch timeline and Lax+POST · The Chromium Projects
  4. 04Bug 1617609: [meta] Enable sameSite=lax by default · Mozilla Bugzilla
  5. 05Cookies: HTTP State Management Mechanism (RFC 6265bis draft), SameSite and Lax-allowing-unsafe · IETF HTTP Working Group
  6. 06Fetch Metadata Request Headers · W3C
  7. 07Sec-Fetch-Site header and browser compatibility · MDN
  8. 08net/http: CrossOriginProtection · Go
  9. 09Go 1.25 release notes · Go
  10. 10OWASP Top 10 2017 release notes (CSRF dropped) · OWASP
  11. 11A01:2025 Broken Access Control (CWE-352) · OWASP
  12. 12Django: Cross Site Request Forgery protection · Django

Last updated