What Is CSRF? Cross-Site Request Forgery Explained (2026)

What Is CSRF? Cross-Site Request Forgery Explained (2026)

You are logged into your online bank. In another tab you open a link from an email, a harmless page with a recipe. You click nothing. Yet in that same second your bank received a transfer of 100 euros, made with your valid login.

What is CSRF? CSRF (cross-site request forgery) is an attack in which a foreign website makes your browser send a request to another website where you are currently logged in. The browser attaches your login cookie automatically, so the server treats the forged request as genuine. The attacker never sees your password and never has to steal your session. They simply exploit the fact that your browser sends it anyway.

In this article we explain CSRF from the ground up: how the attack works, why it worked so well for so long, what the SameSite cookie attribute changed, and which defenses you actually need. We did not rely on documentation for this. On 18 November 2026 we built a small test “bank” on our own server and fired 43 CSRF attacks at it from a real Chrome 157. A few of the results surprised us.

PwnFunction’s animated explainer is from 2019, but the mechanics of the attack have not changed. What has changed is browser behavior, and that is what our test below is about.

What Is CSRF? The Short Answer in Five Sentences

  1. Your browser sends a website’s cookies with every request to that website automatically, no matter which page triggered the request.
  2. An attacker’s page can therefore embed a form, a link or an image that sends a request to your bank, your shop or your admin panel.
  3. The server sees a valid session cookie and performs the action: a transfer, a password change, a new email address, a new user.
  4. The attacker does not get to see the response. CSRF is a “blind” attack: it can trigger actions but cannot read data.
  5. The defense is for the server to recognize where a request comes from: via a secret CSRF token, via the Origin and Sec-Fetch-Site headers, and via the SameSite cookie attribute.

You will also see it written as XSRF, and people often pronounce it “sea-surf”. Same thing.

How a CSRF Attack Works, Step by Step

CSRF is easiest to understand with an example. Take a bank where a transfer is triggered like this:

POST /transfer HTTP/1.1
Host: bank.example
Cookie: sid=8f3a…
Content-Type: application/x-www-form-urlencoded

amount=100&to=DE89370400440532013000

The server checks exactly one thing: does the sid cookie belong to a valid session? If yes, the money moves.

Now an attacker builds this page on evil-recipes.example:

<form id="f" method="POST" action="https://bank.example/transfer">
  <input name="amount" value="100">
  <input name="to" value="DE00ATTACKER">
</form>
<script>f.submit()</script>

That is the whole attack. Anyone who opens the page while logged into the bank submits the form without ever seeing it. Here is what happens:

  1. You log into the bank. The bank sets a session cookie.
  2. You visit the attacker’s page, via a link in an email, an ad or a forum comment.
  3. The attacker’s page triggers a request to the bank. The form is submitted by JavaScript.
  4. The browser attaches the bank cookie, because the request goes to the bank. Under classic cookie rules, it does not matter who triggered it.
  5. The bank sees a valid session and performs the transfer.

Three connected panels: a malicious web page, a browser holding a glowing cookie and a server accepting the request

Step 4 is the key. The attacker can neither read nor steal the cookie, because the browser’s same-origin policy prevents that. But they don’t need to read it. It is enough that the browser sends it.

What CSRF Can and Cannot Do

CSRF is easy to overestimate and just as easy to underestimate. So, to be precise:

CSRF can …CSRF cannot …
trigger actions on the victim’s behalf (transfers, password/email changes, orders, admin actions)read the server’s response
submit forms with arbitrary fieldsread or steal cookies
trigger GET requests via links, images or redirectsset custom headers such as Authorization or X-CSRF-Token (without a CORS grant)
submit login forms (login CSRF)do anything if the victim is not logged in

The right-hand column is why the standard defenses work. Since the attacker’s page cannot set custom headers or read responses, it is enough to require something that only the real site knows or can send.

How CSRF Differs from XSS

CSRF is often confused with XSS (cross-site scripting) because both have “cross-site” in the name. The difference is fundamental:

  • With XSS, the attacker injects their own JavaScript into the target site. The script then runs with all of that site’s privileges and can read data, grab tokens and do anything the user can.
  • With CSRF, the attacker stays on their own site and only sends requests across.

That leads to a hard rule: CSRF protection does nothing against XSS. A script running inside your page can simply read the CSRF token from the HTML and send it along. XSS is therefore the more dangerous flaw. More on vulnerability types and how they are rated in our article on IT security vulnerabilities.

Our Test: 43 CSRF Attacks Against Our Own Test Bank

A lot of what you read online about CSRF was true in 2015. Since then, browsers have fundamentally changed how they handle cookies. We wanted to know what actually happens today, so we measured it ourselves.

The setup:

  • A mini “bank” in Node.js (about 40 lines) on localhost:4801. Logging in sets a session cookie, POST /transfer deducts 100 euros as soon as a valid cookie is present. For every request, the server also logs whether the cookie arrived, plus the Origin, Sec-Fetch-Site and Content-Type headers.
  • An attacker page on port 4802, once served as 127.0.0.1 (a different site to the browser) and once as localhost (the same site, only a different port; more on that shortly).
  • A real Google Chrome 157, driven by Playwright, every attempt in a fresh browser profile.
  • We tested four cookie variants (no SameSite, SameSite=None, Lax, Strict) against five attack techniques.

The five techniques:

  1. form: hidden form submitted by JavaScript (classic POST CSRF)
  2. get: redirect via location = … to a GET URL (top-level navigation)
  3. img: <img src="https://bank/transfer?amount=100">
  4. fetch text/plain: fetch() with mode: "no-cors" and credentials: "include"
  5. fetch JSON: fetch() with Content-Type: application/json

Results from a Foreign Site

This is what happened when the attack came from a different site (127.0.0.1 against localhost). ” executed” means the money was gone.

Cookie settingForm (POST)GET navigation<img>fetch text/plainfetch JSON
no SameSite (browser default) executed* executed no cookie no cookie preflight blocked
SameSite=None executed executed executed executed preflight blocked
SameSite=Lax no cookie executed no cookie no cookie preflight blocked
SameSite=Strict no cookie no cookie no cookie no cookie preflight blocked

* The asterisk marks the most interesting finding of the whole test. More on it in the next section.

Three things can be read directly from this table:

  • SameSite=None is CSRF like it’s 2010. Every technique except JSON works. If you set None because a widget, an iframe or a payment provider needs it, you are deliberately giving up the browser’s protection.
  • Lax stops POST, but not GET. A top-level navigation, meaning a link, a redirect or window.location, carries Lax cookies. That is intentional, so you stay logged in when you click from Google to your shop. But it also means: any action that can be triggered by GET is still vulnerable under Lax.
  • JSON with the correct content type is protected by itself. application/json is not a “simple” content type, so the browser first sends a CORS preflight (OPTIONS). Our server did not answer with a grant, so the actual POST was never sent. text/plain gets no preflight. A server that also accepts “JSON” without the correct header is vulnerable again.

The Two-Minute Window: “Lax by Default” Isn’t Quite Lax

In theory, Chrome has treated cookies without a SameSite attribute as Lax since 2020. Then the form attack in row 1 should have failed. It didn’t: cookie sent, 100 euros gone.

The reason is a little-known exception Chrome calls “Lax+POST”: a cookie without a SameSite attribute is still sent on cross-site top-level POST requests during the first two minutes after it was set. Chrome introduced it so that third-party login flows (single sign-on, payment providers that redirect back via POST) would not break.

We verified this: same setup, but with 130 seconds between login and attack. The server log:

{"method":"POST","cookie":false,"sfs":"cross-site","executed":false}

No cookie, no transfer. In practice this means: if you simply omit the attribute, you have a two-minute window after every login in which classic POST CSRF works. An attacker who lures the victim to their page right after login (say, with a fake “please confirm …” email) hits exactly that window. Always set SameSite explicitly.

The Surprise: Same Site Doesn’t Mean Same Server

Then we ran the same 20 attacks again from localhost:4802, the same hostname, just a different port. The result:

Cookie settingFormGET<img>fetch text/plainfetch JSON
none / None / Lax / Strict preflight

Even SameSite=Strict blocked nothing. The server log shows why: Sec-Fetch-Site: same-site.

To a browser, “site” is not the same as “origin”:

  • Origin = scheme + host + port. https://shop.example:443 and https://admin.example:443 are two different origins.
  • Site = scheme + registrable domain. https://shop.example.com and https://blog.example.com are the same site. Ports don’t count at all.

So SameSite only protects you from other domains, not from other subdomains and not from other ports. In practice that matters more than it sounds:

  • If blog.yourcompany.com runs an outdated WordPress with an XSS hole, an attacker can use it to send SameSite cookies for shop.yourcompany.com.
  • If you give users their own subdomains (customer1.yourservice.com), every customer page is the “same site” as your dashboard as far as SameSite is concerned. Platforms that take this seriously register with the Public Suffix List, so their subdomains count as separate sites.
  • A test or staging server on a subdomain of your production domain belongs to the same site as production.

That makes SameSite a good second line of defense, but not a defense on its own.

Three glowing doors in a row with different locks: the first wide open, the second half open, the third firmly locked

And with Real Protection?

Finally, we added three server-side checks and tested them against the most dangerous case: SameSite=None, form attack from a foreign site. The cookie arrived in all three cases. Nothing was executed anyway:

Server-side checkCookie sent?Executed?
CSRF token required in the formyes 403 Forbidden
Origin must be http://localhost:4801yes 403 Forbidden
Sec-Fetch-Site must be same-origin or noneyes 403 Forbidden

Each of the three checks stopped the attack even though the browser blocked nothing. That is the principle of CSRF protection in one table: security comes from the server, not from the cookie.

One caveat on scope: this was a test with a single browser (Chrome 157) on localhost. Firefox and Safari have partly different defaults; Safari, for instance, has blocked third-party cookies across the board for a long time. The server-side checks work regardless of the browser, and those are what matter.

How to Prevent CSRF: The Defenses at a Glance

The good news: CSRF is one of the best-understood web vulnerabilities. The defenses are well known and most frameworks ship them. What matters is not switching them off by accident.

1. CSRF Tokens (Synchronizer Token Pattern)

The classic, and still OWASP’s primary recommendation:

  1. The server generates a random, unguessable value per session (or per form).
  2. It embeds it in every form as a hidden field, or exposes it in a meta tag for JavaScript requests.
  3. On every state-changing request, the server checks that the submitted value matches the session.
<form method="POST" action="/transfer">
  <input type="hidden" name="csrf" value="b7e1c9…">
  …
</form>

Why it works: the attacker’s page can submit the form, but it does not know the token. To get it, it would have to read the bank’s page, which is exactly what the same-origin policy prevents.

Implementation details that matter:

  • The token must be cryptographically random (crypto.randomBytes, random_bytes, secrets.token_hex), not a timestamp and not the user ID.
  • Compare with a constant-time function.
  • The token never goes in the URL, or it ends up in logs, browser history and the Referer header.
  • A missing token must be rejected, not just a wrong one. A common bug is a check along the lines of “if a token is present, compare it”.

A variant for applications without server-side session storage: the server also sets the token as a cookie, and the frontend must repeat it in a header (e.g. X-CSRF-Token) on every request. The server compares cookie and header.

The attacker’s page cannot read the cookie, so it cannot fill in the header. The naive variant has a weakness, though: anyone who can set a cookie on your domain, for instance through a compromised subdomain (see above, same site), can supply a matching cookie and header. OWASP therefore recommends the “signed” variant, where the token is bound to the session with an HMAC.

3. Check the Origin and Sec-Fetch-Site Headers

Modern browsers send metadata with every request that a page cannot forge. In our test they arrived reliably with every attack:

  • Origin: on POST requests, the browser includes the origin the request came from. Every form attack in our log carried Origin: http://127.0.0.1:4802.
  • Sec-Fetch-Site: one of same-origin, same-site, cross-site or none (bookmark, typed URL). All current browsers support it.

A lean defense in Express looks like this:

app.use((req, res, next) => {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
  const site = req.get('sec-fetch-site');
  if (site && site !== 'same-origin' && site !== 'none') {
    return res.status(403).send('Cross-site request blocked');
  }
  const origin = req.get('origin');
  if (!site && origin && origin !== 'https://your-domain.com') {
    return res.status(403).send('Bad origin');
  }
  next();
});

This approach is called “Fetch Metadata Resource Isolation”. It is simple, needs no form field and also protects against attacks from your own subdomains, because same-site is not let through. Very old browsers without these headers can be covered by the Origin check or additionally by tokens.

Behind a reverse proxy, make sure the proxy passes these headers through. nginx and Caddy do by default, but custom header filters can strip them by accident.

4. Set SameSite Cookies Explicitly

Even though SameSite is not complete protection, you should always set it explicitly, if only because of the two-minute window from our test:

Set-Cookie: sid=…; Path=/; Secure; HttpOnly; SameSite=Lax
  • Lax is the right default for most login cookies: links from elsewhere work, cross-site forms and embedded requests get no cookie.
  • Strict is safer, but with a drawback you notice immediately: someone clicking through to your shop from another site (say, an email) is not logged in on that first page view. Sensible for admin panels and banking.
  • None only if your cookie is genuinely needed in foreign contexts, and then only together with a token or origin check. None also only works with Secure, meaning only over HTTPS.

5. Never Change State with GET

The simplest rule of all, and our test shows why it matters: GET requests must not change anything. No /logout?confirm=1, no /admin/delete?id=5, no /newsletter/unsubscribe without a confirmation form. GET is the one method that even SameSite=Lax lets through on top-level navigation, and it is also triggered by images, link previews, prefetching and bots.

6. Require Re-Confirmation for Critical Actions

For high-impact actions such as a password change, a new email address or deleting an account, the most reliable safeguard is re-authentication: current password, 2FA code or passkey. That helps not only against CSRF but also against stolen sessions and unlocked computers.

A server hands a browser a unique glowing ticket, while a forged letter without a ticket is stopped by a shield at the gate

From June 2026: Aikido Security explains the attack with an everyday analogy and walks through the defenses.

Do APIs with Token Authentication Need CSRF Protection?

This question comes up constantly, and the answer depends on where the credential lives:

  • Token in the Authorization header (Bearer …) or a custom header like x-session-token: not vulnerable to CSRF. Browsers never attach such headers automatically. An attacker would need to know the token to send it. For APIs built for programs, this is the norm.
  • Token in a cookie (including a JWT in a cookie): vulnerable to CSRF, just like a classic session. What is inside the cookie doesn’t matter, only that the browser sends it automatically.
  • HTTP Basic Auth and client certificates: also vulnerable, because the browser repeats these automatically as well.

An example from our own practice: the dashboard of our analytics tool Tacilytics stores the session token in the browser and sends it with every request in a custom x-session-token header. There is no login cookie. An attacker’s page cannot set that header without knowing the token, so CSRF is ruled out by design.

That decision has a price worth naming honestly: a token in localStorage is readable by JavaScript. An XSS flaw would expose it immediately, while an HttpOnly cookie stays invisible to scripts. You trade CSRF exposure for bigger XSS consequences. Both approaches are defensible if you take the other defense seriously: cookies need CSRF protection, header tokens need a strict Content Security Policy and clean escaping.

What About CORS?

A common misconception: “We locked down CORS, so we’re safe from CSRF.” Not true. CORS controls whether a foreign page may read the response, not whether the request arrives. In our test, the text/plain fetch with mode: "no-cors" reached the server and was executed, even though we had set no CORS headers at all. The attacker’s page just couldn’t see the response, and CSRF doesn’t need it.

CORS only helps indirectly: requests with application/json or custom headers trigger a preflight, and without a CORS grant the actual request is never sent. By the way, Access-Control-Allow-Origin: * combined with Allow-Credentials is not even permitted, but a “dynamically reflected” origin header is, and that cancels this protection completely.

Login CSRF: The Underrated Special Case

A variant few people think about: the attacker logs you into their own account. Their page submits your service’s login form with their credentials.

It sounds harmless, but it isn’t. If you don’t notice you’re in the wrong account, your input goes to the attacker: search history, saved credit cards, uploaded documents, stored addresses. Years ago this exact attack was used against Google to record victims’ search histories in the attacker’s account.

The defense is the same: the login form also needs a CSRF token or an origin check. Many implementations skip it because “there’s no session before login yet”. A pre-session or a signed cookie is enough for the token.

Where CSRF Still Shows Up Today

So is CSRF solved thanks to SameSite and framework protection? Not quite. Typical places where it still appears:

  • Custom endpoints next to the framework, like a quickly written admin-action.php that bypasses the framework’s form protection.
  • Disabled checks. The classic in Laravel is an entry in the CSRF middleware’s $except array, in Django a @csrf_exempt, “because the webhook won’t work otherwise”. Webhooks do need an exception, but then they need their own signature check.
  • Routers, NAS boxes and smart-home devices on your home network. Their web interfaces are often protected neither against CSRF nor against DNS rebinding, and a website on the internet can send requests to 192.168.0.1. Recent Chrome versions now ask for permission (“Local Network Access”); older devices and browsers don’t.
  • SameSite=None for embedding. Anyone embedding their app in customers’ iframes often needs None, and then forgets the token check.
  • GET endpoints that change things. See above: Lax does not help against GET navigation.
  • Switching from token auth to cookies. Moving a single-page app’s token from localStorage into an HttpOnly cookie is the right call against XSS, but it reintroduces CSRF unless you add a check at the same time.

CSRF has not had its own slot in the OWASP Top 10 since 2017, because frameworks cover it so well. In the current list it falls under A01 Broken Access Control. That is no acquittal: it just means the flaw today mostly appears where someone departs from the defaults.

How to Test Your Own Application for CSRF

You don’t need a pentesting firm for this. A quick self-test in five steps:

  1. Look at your cookies. In the developer tools (F12), under “Application” or “Storage” → Cookies: does your session cookie have SameSite=Lax or Strict? If nothing is listed, that is item one on your list.
  2. Find state-changing requests. Perform an action in the Network tab (save a profile, add to cart, change password) and inspect the request: is there a token field or a header like X-CSRF-Token?
  3. Remove the token. Copy the request with “Copy as cURL”, delete the token field and resend it. If you get anything other than a 403 or 419, the check has gaps.
  4. Spoof the origin. Send the same request with -H "Origin: https://evil.example" and -H "Sec-Fetch-Site: cross-site". A properly protected server rejects it.
  5. Build a real test page. Put the HTML form from above on a different domain (not a subdomain!), stay logged in in a second tab and open the test page. That is the test that counts in the end.

And importantly: only test applications you own or have explicit permission to test. “Trying out” CSRF on someone else’s service triggers real actions in real people’s accounts.

What We Did Not Test

So the numbers above are read correctly, here are the limits of our test:

  • Only Chrome 157. We did not measure Firefox or Safari, whose default behavior for cookies without SameSite partly differs.
  • The test ran over HTTP on localhost, which Chrome treats as a secure context. We expect the same behavior over real HTTPS with two real domains, but we did not measure it.
  • No extensions, no enterprise policies, no third-party cookie blocking in browser settings. Users who block third-party cookies entirely are protected in some of the cells above, but no server should rely on that.
  • We only described login CSRF and attacks on home networks; we did not reproduce them.

FAQ: Common Questions About CSRF

What is CSRF in simple terms?

CSRF is an attack in which a foreign website secretly makes your browser send a request to a site where you are logged in. Because the browser sends your login cookie automatically, the server performs the action as if you had clicked yourself.

What does CSRF stand for?

CSRF stands for cross-site request forgery. Other names are XSRF, “session riding” and “one-click attack”.

What is a CSRF token?

A CSRF token is a random, secret value that the server embeds in every form and requires back on every request. A foreign page cannot read the value and therefore cannot build a valid request.

What does “CSRF token mismatch” or “invalid CSRF token” mean?

The error means the submitted token does not match the current session. It is usually harmless: the page was open too long and the session expired, you logged in again in another tab, or cookies are being blocked. Reloading and resubmitting almost always helps. As a developer, check whether caching (for example a CDN caching form pages) is serving the same stale token to every user.

Is SameSite=Lax enough to prevent CSRF?

No. Our test shows three gaps: GET requests via navigation get through, attacks from subdomains or other ports count as “same site”, and cookies with no attribute at all are vulnerable to POST for the first two minutes after login. Lax is a good second layer; the real protection should live on the server.

What is the difference between CSRF and XSS?

With XSS, injected code runs inside the target site and can read and do anything. With CSRF, the attacker stays on their own site and can only blindly send requests across. XSS is more dangerous and defeats any CSRF protection.

Are REST APIs vulnerable to CSRF?

Only if they authenticate via cookies, Basic Auth or client certificates. APIs using Authorization: Bearer … are not vulnerable, because the browser never sets that header on its own. Watch out for APIs that also accept JSON with Content-Type: text/plain: that removes the preflight protection.

Does HTTPS protect against CSRF?

No. HTTPS encrypts the connection, but the forged request also arrives encrypted and with a valid cookie. HTTPS is still a requirement for Secure cookies and SameSite=None.

Do WordPress, Laravel and similar have built-in CSRF protection?

Yes. WordPress uses so-called nonces; Laravel, Symfony, Django and Rails enable token middleware by default. Shopware 6 dropped its storefront form tokens in version 6.5 and has relied on SameSite cookies since, one more reason to know the limits of SameSite from our test. The gaps almost always appear in plugins and custom extensions that don’t call the check. For WordPress plugins, missing nonce checks are among the most frequently reported vulnerabilities of all.

How can I tell as a user that I’ve been hit by CSRF?

Usually you can’t, and that is exactly what makes it dangerous. It helps to log out after using banking or admin panels, to use them in a separate browser profile, and not to open unknown links in the same browser where you’re logged into important services.

Floating glowing shield icons above a laptop showing a secured web application

Conclusion: What Is CSRF, and What Should You Do Now?

CSRF exploits a single property of the web: the browser sends cookies no matter who triggered the request. Browsers have defused this considerably with SameSite, but our test shows that protection has holes: GET navigation, subdomains and ports, a two-minute window after login, and any application that deliberately sets SameSite=None.

The checklist for your own application:

  1. Set session cookies explicitly with SameSite=Lax (or Strict for admin areas), plus Secure and HttpOnly.
  2. Check on the server: CSRF token or Sec-Fetch-Site/Origin, ideally both. Reject missing values, don’t wave them through.
  3. Never change anything via GET.
  4. Review framework exceptions critically. Every csrf_exempt needs its own protection, such as a webhook signature.
  5. Have critical actions like password or email changes re-confirmed with a password, 2FA or a passkey.
  6. Take XSS seriously, because it defeats any CSRF protection.

If you want to harden your servers further, we have matching guides: understanding and setting up HTTPS, fail2ban against automated attacks, and an overview of the most common IT security vulnerabilities.