Skip to main content
Security guideReviewed

CSRF: how cross-site request forgery works, and the three checks that refuse it

Cross-site request forgery gets a signed-in visitor's browser to send a request they never meant to send.

This guide explains in plain English why browsers make that possible, what CSRF tokens, Origin and Sec-Fetch-Site checks and SameSite cookies each do, and where each one stops. It comes with a request matrix and a lab you can run on your own machine with Node.js alone.

State-changing request matrix and CSRF lab

An illustration on invented hosts and a made-up account. Part 1 is a matrix of eight ways a request can reach a state-changing endpoint, with what a browser sends in each, sourced row by row, and what an anti-forgery token, an Origin or Sec-Fetch-Site check and SameSite each do, for cookie and bearer authentication.

How to use it

Parts 2 to 6 are a Node.js lab with no installs: a server with switchable checks, a scripted client that stands in for the browser, a regression test that fails when a check is switched off, and steps to see what your own browser sends. Run it on your own machine, for learning and for testing code you own.

csrf.txt

Introduction5 lines

ILLUSTRATION ONLY. The account, its display name, the hosts app.example.com, blog.example.com and other.example.net, and every request below are invented for this page. The lab runs on your own machine, binds to 127.0.0.1, keeps everything in memory and can change nothing but a made-up display name. Use it for learning and for testing code you own. What this asset is, and what it is not. Part 1 is a matrix of what a browser sends in eight situations, taken from the documents named in each row, and what each check does with it. Parts 2 to 4 are a lab whose scripted client stands in for the browser and sends the cookie and headers Part 1 lists. The lab proves what a server does with each set of headers. It does not prove what any browser sends: the sources do that, and Part 5 shows you how to watch your own browser. Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test and node:assert, which ship with Node.js, so there is nothing to install. Every output below comes from that run; timings and ports will differ on your machine.

What CSRF is

Picture a customer portal where a signed-in customer can change the email address their invoices go to.

The change is one request: the browser sends the new address to the server, together with the cookie that says who is signed in. Cross-site request forgery, shortened to CSRF, is when a different website gets that customer's browser to send the same request, with the same cookie, without the customer meaning to. The server sees a signed-in customer asking for a change, and makes it.

OWASP's Cross-Site Request Forgery Prevention Cheat Sheet defines the attack as one where a malicious web site, email, blog, instant message or program tricks an authenticated user's web browser into performing an unwanted action on a trusted site, and says an unprotected site cannot tell legitimate requests from forged authenticated ones.

It also sets the limit: the attacker can only use what the vulnerable application exposes and what the user is allowed to do. Depending on the user, that can mean transferring funds, changing a password, making a purchase or raising an account's privileges.

MITRE catalogues the weakness as CWE-352, Cross-Site Request Forgery, and describes it as a web application that does not, or cannot, sufficiently verify whether a request was intentionally provided by the user who sent it. It lists Session Riding and XSRF among its other names.

CWE-352 says the scope of an attack is limited only by the victim's privileges, and that when the victim is an administrator the consequences may include complete control over the web application.

The OWASP Top 10:2025 names CWE-352 among the notable weaknesses in A01 Broken Access Control, and MITRE lists it in its 2025 CWE Top 25 Most Dangerous Software Weaknesses.

There is no single setting that fixes it. This page explains the three checks that refuse a forged request (an anti-forgery token, a check of where the request came from, and the SameSite cookie attribute), what each one leaves behind, and how bearer tokens change the picture.

Three neighbouring topics have their own guides: cookie security covers every cookie attribute, CORS misconfiguration covers which other sites may read your responses, and session management covers how sessions start, rotate and end.

Why browsers make CSRF possible

The root of the problem is that the browser attaches cookies by itself.

The OWASP cheat sheet puts it in one line: browser requests automatically include all cookies, including session cookies. OWASP's test for CSRF, WSTG-SESS-05, describes the same mechanism: once the browser receives a site's cookie, it automatically sends it along with any further requests directed to that site.

The guide lists three ways the same GET request can arrive, through the application itself, from a URL typed into the browser and from a link on another site, and says the application cannot tell them apart.

So a session cookie proves which browser sent a request, not which page asked the browser to send it. WSTG-SESS-05 says CSRF relies on session management that uses only information known by the browser, which it describes as information such as cookies or HTTP-based authentication, for example Basic Authentication, that the browser stores and presents with each request.

MDN's CSRF guide gives the conditions in plainer words: in general, a site is open to CSRF if it uses HTTP requests to change state, uses only cookies to check that a request came from a signed-in user, and uses only parameters an attacker can predict.

The web was also built to let one site send requests to another. MDN's page on the same-origin policy says cross-origin writes, such as links, redirects and form submissions, are typically allowed, while cross-origin reads are typically disallowed. A form on any website can post to yours, and MDN's CORS guide explains that this is why a request that looks like a form submission needs no permission from the receiving server before it is sent.

The other site cannot read your response unless your server opts in with CORS headers, but the request still reaches your server.

Each defence on this page works by finding something a forged request cannot supply: a secret value from your own page, the browser's own statement of where the request came from, or the session cookie, which the browser declines to send.

CSRF prevention: the three checks

The OWASP cheat sheet's first instruction is to check whether your framework has built-in CSRF protection and use it.

Where it does not, add CSRF tokens to all state-changing requests and validate them on the server. Software that targets only modern browsers may rely on Fetch Metadata headers instead, with a fallback, and the cheat sheet asks for at least one defence-in-depth measure on top, SameSite among them. MDN's CSRF guide takes the same line, describing SameSite as an addition to a primary defence rather than a complete one.

Anti-forgery tokens (CSRF tokens)

A CSRF token is an unpredictable value the server places in its own page and expects back with each state-changing request. 2 min read

Origin and Sec-Fetch-Site checks

The second check asks the browser where the request came from. 2 min read

SameSite cookies

The third check lives in the cookie. 2 min read

Same site is not the same as same origin

SameSite is decided by site, and a site is wider than an origin.

MDN defines an origin as the scheme, hostname and port of a URL, and gives http://example.com and http://example.com:8080 as two URLs that are not the same origin because their ports differ. A site is defined by the registrable domain. MDN's glossary says support.mozilla.org and developer.mozilla.org are the same site, and that https://example.com:8080 and https://example.com are the same site because the port is ignored when determining the site.

The HTML Standard builds a site from the scheme and the registrable domain and ignores the port, and adds that same-site concepts should be avoided where possible in favour of same-origin checks.

The rules for SameSite cookies use the schemeful version, which also compares the scheme, so http://example.com and https://example.com count as different sites.

That gap matters for CSRF. Two ports on one host are the same site but different origins, and so are app.example.com and blog.example.com. A form on either can post to the other, and every SameSite value, Strict included, lets the session cookie through, because to the browser it is a same-site request.

The OWASP cheat sheet spells out the consequence: a cookie set on app.example.com with any SameSite value is still sent with requests from anything.example.com, so a vulnerability or a malicious actor on any sibling host can send requests your SameSite cookies accompany, and a taken-over subdomain inherits the same reach. MDN's CSRF guide concludes that relying on same-site protection means trusting all your site's subdomains.

Sec-Fetch-Site draws the finer line. MDN says same-origin means the same scheme, host and port, and same-site means the same site, including the scheme. The Fetch Metadata draft sets same-origin only when every URL in the request's URL list, redirects included, is same-origin with the request's origin.

A check that accepts only same-origin, as the lab on this page does, refuses the sibling subdomain and the other port. A check that also accepts same-site does not. Rows S7 and S8 of the matrix show both.

Before you decide whether to trust same-site requests, list what shares your registrable domain. The cheat sheet's list of hosts to think about includes multi-tenant services on a shared parent domain, user content served from subdomains, legacy subdomains, an acquired product on the same parent domain and third-party services on subdomains.

To that, add anything you run on another port of the same host. ASVS 5.0 requirement 3.5.4, at Level 2, asks that separate applications are hosted on different hostnames, which keeps them apart under the same-origin policy and hostname-based cookie rules.

Why a GET request must not change anything

The OWASP cheat sheet, MITRE and the ASVS all state this rule.

The OWASP cheat sheet says not to use GET requests for state-changing operations. CWE-352 lists not using the GET method for any request that triggers a state change among its mitigations. ASVS 5.0 requirement 3.5.3, at Level 1, asks that requests to sensitive functionality use methods such as POST, PUT, PATCH or DELETE rather than safe methods such as GET, or that strict validation of the Sec-Fetch headers takes their place.

A GET is the easiest request to forge. WSTG-SESS-05 shows an invisible img tag whose src points at an action on the target: the browser fetches it to display the image, and the request carries the session cookie.

MDN's CSRF guide uses the same example for a funds transfer. A link works as well, and a link is a top-level navigation with a safe method, which is exactly what SameSite=Lax lets through.

The cheat sheet puts this first in its list of SameSite's limitations: Lax only blocks unsafe methods, so it does not stop a state-changing operation that is reachable by GET.

A GET also carries less evidence. The Fetch Standard adds an Origin header to a cross-origin request made in CORS mode (response tainting cors), or to one whose method is neither GET nor HEAD, so a cross-site link or image request arrives with no Origin at all, and a check that relies on Origin has nothing to compare.

Sec-Fetch-Site is still sent, but the cheat sheet's own policy lets cross-site GET navigations through, so that other sites can link to yours.

Moving the change to POST is not the whole fix either. WSTG-SESS-05 says POST requests can be automated with JavaScript, so using POST alone is not enough. MDN warns that some web frameworks support method override, which lets a request sent with GET appear to the server as a POST, so check that any override in your framework does not accept a GET.

Next.js makes a related point for its own apps: its data security guide says mutations should never be a side effect of rendering, and shows a page that deletes a cookie when a logout search parameter is present as the example of what not to do.

Bearer tokens: what changes and what does not

An API can authenticate each call with a bearer token instead of a session cookie.

RFC 6750, the OAuth 2.0 bearer token standard, says clients should send the token in the Authorization request header field using the Bearer scheme. In a browser, that means your own JavaScript adds it to each request.

That changes the CSRF picture, because a bearer token is not something the browser sends on its own. It is not a cookie, and it is not the stored HTTP authentication that WSTG-SESS-05 says CSRF relies on. MDN's CSRF guide lists using only cookies to check who sent a request as one of the conditions under which, in general, the attack is possible.

A page on another site can still make the browser send a request to your API, but it cannot read your token: MDN's same-origin policy page says each origin gets its own separate storage, and JavaScript in one origin cannot read storage belonging to another.

The forged request arrives without the header and fails authentication. Setting G of the lab shows that result for every row.

A bearer token moves the risk rather than removing it. These are the gaps that stay open.

  • Cross-site scripting. The OWASP cheat sheet warns that XSS can defeat all CSRF mitigation techniques, and a token kept where JavaScript can read it can be read by injected script too. OWASP's HTML5 Security Cheat Sheet says one cross-site scripting flaw can be used to steal all the data in local storage, and advises against keeping session identifiers there because the data is always accessible by JavaScript. The XSS guide covers prevention.
  • A cookie fallback. If the same API also accepts the session cookie, for example because the web app and the API share a login, a forged request can take the cookie path and every row of the matrix applies again. Check every way each state-changing endpoint accepts a caller.
  • A token kept in a cookie. RFC 6750 says implementations that store bearer tokens in cookies must take precautions against cross-site request forgery. At that point it is a session cookie by another name.
  • A token in a URL. RFC 6750 says bearer tokens should not be passed in page URLs, such as query strings, because browsers, servers and other software may not adequately protect URLs in history, logs and other data structures.

Login CSRF: forging the sign-in itself

Sign-in forms get overlooked because the visitor is not signed in yet.

The OWASP cheat sheet says CSRF can still happen on a login form, with a different impact. Its example: an attacker uses CSRF to sign the victim into a shopping site with the attacker's own account, the victim then enters their card details, and the attacker may be able to buy items with the victim's stored card.

The same applies to anything else a victim saves while unknowingly signed in as someone else, such as an address or a document.

The cheat sheet's fix is a pre-session: create a session before sign-in and put a token in the login form, then at sign-in destroy that pre-session and create a new session, so it cannot be used for session fixation. A custom request header on an AJAX login also works. The cheat sheet notes that checking the Referer when Origin is absent is also used for requests made before a session exists, so an Origin or Sec-Fetch-Site check belongs on the login endpoint as much as on any other. How sessions rotate at sign-in is covered in the session management guide.

What each fix leaves behind

No check covers every row of the matrix, and each has gaps of its own.

These are the ones the sources name.

Anti-forgery tokens

Script on your own page. 1 min read

Origin and Sec-Fetch-Site checks

Missing or altered headers. 1 min read

SameSite cookies

GET, siblings and defaults. 1 min read

When SameSite alone might be enough

The cheat sheet sets out narrow conditions under which SameSite alone can be a reasonable defence, and all of them have to hold: the application shares no registrable domain with any host you do not fully control; no GET or other safe-method endpoint changes state; the session cookie is Strict, or Lax with the __Host- prefix and an audit of every GET handler; Origin or Referer verification is in place as well; and you accept the risk for users whose browsers do not enforce SameSite. 1 min read

Running the CSRF lab on your own machine

The lab is an illustration.

One invented account has a display name and one endpoint that changes it, so the most a forged request can do is rename a made-up account on your own machine. The server binds to 127.0.0.1, lets the system pick a free port, keeps everything in memory and uses only modules that ship with Node.js, so there is nothing to install.

It was written and run on Node.js 26.0.0, and every output in the asset comes from that run. Use it for learning and for testing code you own.

Be clear about what it proves. The scripted client stands in for the browser: for each matrix row it sends the cookie and headers that the documents in the matrix say a browser sends in that situation, under seven server settings.

The output shows what a server does with each set of headers. It does not show what a browser sends. The documents establish that, and the browser check lets you watch your own browser do it.

  • Save the four files into an empty folder and open a terminal there.
  • Run node run-matrix.mjs. For each of the eight situations it prints the request it sends and the server's response under settings A to G: no checks, SameSite=Lax only, SameSite=Strict only, the Origin and Sec-Fetch-Site check only, the token check only, all three together, and a bearer token instead of a cookie.
  • Run node csrf-checks.test.mjs. All nine tests pass. Run it again with token-off, origin-off, samesite-off or get-on, and the tests for that check fail and the process exits with code 1, so a pipeline step running the test fails if someone switches a check off.
  • Run node browser-check.mjs, open the three addresses it prints in turn, and post the form from each one.

Checking the browser side in developer tools

In browser-check mode the token and origin checks are off, so the result depends only on whether your browser sent the session cookie. Open the developer tools, choose the Network panel, post the form and click the request to /account/display-name. Under the request headers, read Origin, Sec-Fetch-Site and Cookie. The terminal prints the same three values for each post, with the server's result.

The first address is the account page on the lab's own origin; compare it with row S1. The second is another port on 127.0.0.1, which is a different origin but the same site; compare it with row S8. The third reaches that second server as localhost, which is a different site from 127.0.0.1, because the HTML Standard builds the site from the whole host when there is no registrable domain and the URL Standard gives an IP address none; compare it with row S2.

Then repeat with the Strict and unset options.

If your browser sends something the matrix does not describe, record the browser and version: your browser is the evidence for this part.

Pointing the regression test at your own code

Keep the nine tests and change two things: start your own application on a test port with a seeded test account in place of the lab server, and use one of your own state-changing endpoints in place of the display-name endpoint.

Keep one test per check, with the other check's input held valid, so a failure names the check that stopped working, and add the GET test for every state-changing endpoint.

CSRF protection in your framework

Start with what your framework already does, as the cheat sheet advises, because built-in defences are maintained by the framework's authors.

Its examples: .NET has built-in token protection and leaves key and token management to you, and from Go 1.25 the standard library's CrossOriginProtection type implements a Fetch Metadata defence. MDN gives Django's csrf_token template tag as an example of token support, and notes that using it means understanding every place your site sends state-changing requests.

In Next.js, Server Actions accept only POST and compare the Origin header with the Host header, or X-Forwarded-Host, aborting the request on a mismatch, according to the Next.js data security guide. The guide recommends serverActions.allowedOrigins to list safe origins for large applications that use reverse proxies or multi-layered backend architectures, where the server API differs from the production domain.

The Next.js guide on this site covers how that check is tested. For anything else in a Next.js app that changes state, such as a route handler, confirm which of the three checks it runs.

Whatever the framework, list your state-changing endpoints and confirm each is covered, including any added outside the framework's usual path, and keep the cheat sheet's explicit list of exemptions, such as a webhook another server calls, with what protects each one instead.

How to test for CSRF in your own application

OWASP's testing guide covers this in WSTG-SESS-05, Testing for Cross Site Request Forgery, with one objective: determine whether it is possible to initiate requests on a user's behalf that are not initiated by the user.

Its first step is an audit of session management. If the session relies only on client-side values, meaning cookies or HTTP authentication credentials, the guide says the application is vulnerable.

  • List every endpoint that changes state: forms, API calls, Server Actions and route handlers, including sign-in, sign-out and settings.
  • For each one, on a copy you own and with a test account, send the requests the regression test sends: no token, a wrong token, Sec-Fetch-Site cross-site and same-site, no Sec-Fetch-Site with a foreign or null Origin, and a GET with the same parameters. A refusal is the pass; a changed record is the evidence when it is not.
  • Check content types. WSTG-SESS-05 shows a form with the text/plain encoding delivering a JSON-looking body, and the cheat sheet says an API that accepts text/plain would be open to CSRF. Its mitigation is to refuse the simple content types, application/x-www-form-urlencoded, multipart/form-data and text/plain, on endpoints that expect JSON. ASVS 5.0 requirement 3.5.2 asks for the same outcome when you rely on the CORS preflight.
  • Read the Set-Cookie header of the session cookie and confirm SameSite is set on purpose. ASVS 5.0 requirement 3.3.2, at Level 2, asks that each cookie's SameSite value is set according to the cookie's purpose.
  • Test only systems you own or are authorised in writing to test, using test accounts and test records.

Where an outside test fits

Your own tests check the endpoints you know about.

A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. For a Next.js application, state-changing Server Action requests are sent with a foreign Origin header and with Origin set to null, and both should be rejected, as the Next.js guide in this library describes.

The website security check, which does not sign in, reviews the cookie settings anyone can see, including whether a SameSite value was chosen deliberately rather than left to the browser.

Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

Cross-site request forgery is when another website makes your signed-in visitor's browser send a request to your site that the visitor never meant to send, such as changing their email address. The browser attaches the session cookie by itself, so the server sees a signed-in user and acts. CWE-352 describes the weakness as an application that does not, or cannot, sufficiently verify whether a request was intentionally provided by the user who sent it.

A secret, unpredictable value the server puts in its own page and expects back with every state-changing request. The OWASP cheat sheet says it should be generated on the server, unique per session, secret and unpredictable, and that a request with a missing or mismatched token should be rejected. Browsers block another site from reading your page by default, and as long as you do not open that up (for example with a permissive CORS policy), it cannot include the token in a forged request.

They reduce it. Strict and Lax keep the cookie off cross-site POST requests, but Lax still sends it on a top-level GET navigation, and no SameSite value stops a request from a sibling subdomain or another port, because those are the same site. MDN, the OWASP cheat sheet and the cookie draft all describe SameSite as defence in depth alongside a token or an origin check.

Origin names the origin that caused the request, and your server compares it with its own. Sec-Fetch-Site states the relationship directly: same-origin, same-site, cross-site or none. Browsers send Sec-Fetch-Site only to potentially trustworthy URLs, and MDN says user agents do not add Origin to a cross-origin GET in no-cors mode. The OWASP cheat sheet treats Sec-Fetch-Site as the primary signal and, because some legacy browsers do not send it, makes a fallback to Origin, then Referer, mandatory.

Not immune, but a forged request has nothing to authenticate with if the token travels only in an Authorization header your own script adds, because the browser does not attach it and another origin cannot read your storage. It stops applying if the API also accepts a session cookie or the token is kept in a cookie, and cross-site scripting can steal a token that JavaScript can read.

It is necessary but not enough. A GET that changes state can be forged with a link, which gets through SameSite=Lax, or with an image tag, which carries the cookie when it has no SameSite restriction and the browser allows third-party cookies, so state changes belong on POST, PUT, PATCH or DELETE. But WSTG-SESS-05 notes that POST requests can be automated with JavaScript, so a POST endpoint still needs a token or an origin check.

A forged sign-in that logs the victim into the attacker's account, so whatever the victim then saves, such as card details, lands in an account the attacker controls. The OWASP cheat sheet recommends a token in the login form tied to a pre-session that is replaced by a new session at sign-in, or a custom request header on an AJAX login.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.