00->1
Learning pathStep 51 of 62Web application attacks and the OWASP Top 10 ← All writeups

Cross-Site Request Forgery (CSRF), Explained

If you are reading this, you have probably seen "CSRF" or "XSRF" in a web security course, and you want to understand why a site can be attacked just because you visited another page, and what actually stops it.

By the end you will be able to explain how CSRF works, list the three conditions it needs, say what it can and cannot do, tell it apart from XSS, and apply the defences in the right order. It builds on the OWASP Top 10 overview and on the basics of cookies and HTTP in Computer and Networking Basics. Everything here is for understanding and for practice on labs you own or are allowed to test.


1. What CSRF is

PortSwigger defines cross-site request forgery as a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.

To see why that is possible, remember how login works. After you log in to a site, it gives your browser a session cookie. From then on, the browser attaches that cookie automatically to every request to that site, no matter which page caused the request. The server sees the cookie and thinks: "this is the logged-in user."

That "no matter which page" is the problem. If you are logged in to bank.example and then open evil.example in another tab, a page on evil.example can cause your browser to send a request to bank.example. Your browser will add your bank cookie, and the bank cannot tell whether you clicked its own button or the attacker's page triggered the request.

The attacker never sees your cookie and never logs in. They borrow your browser, which is already logged in.

In the OWASP Top 10:2025, CSRF is one of the weakness types mapped to A01 Broken Access Control.

A picture

You hand your assistant a signed blank cheque book so they can handle your payments. A stranger gives the assistant a note: "Please write a cheque to me." The assistant, who cannot tell who wrote the note, does it, because the cheque book is signed by you. The cookie is the signed cheque book; the stranger's note is the forged request.


2. The three conditions

PortSwigger lists three conditions that must all be true for a CSRF attack to work:

Condition In plain words
A relevant action There is something worth doing: changing an email address or password, transferring money, adding an administrator
Cookie-based session handling The application relies only on the session cookie to know who is making the request, with no other check
No unpredictable request parameters The attacker can work out every value the request needs. If the request also needs a secret the attacker cannot know (such as the current password), the attack fails

Removing any one of the three stops the attack. The defences in this post each break one of them.


3. An example, step by step

Suppose shop.example lets a logged-in user change their email address with this request:

POST /account/email HTTP/1.1
Host: shop.example
Cookie: session=abc123
Content-Type: application/x-www-form-urlencoded

email=me@example.com

All three conditions hold: changing the email is a useful action (the attacker can then use "forgot password" to take over the account), the site identifies the user only by the cookie, and the only parameter, the new email, is something the attacker can choose.

The attacker builds a page on their own site:

<form action="https://shop.example/account/email" method="POST">
  <input type="hidden" name="email" value="attacker@evil.example">
</form>
<script>document.forms[0].submit();</script>

The attacker tricks the victim into opening it, usually with a link in a message (phishing, smishing) or by placing it on a page the victim is likely to visit. When the victim, who is logged in to shop.example, loads the page:

  1. The script submits the hidden form.
  2. The victim's browser sends the POST to shop.example.
  3. The browser adds the victim's session cookie, since the request goes to shop.example.
  4. The server sees a valid session and a valid-looking request, and changes the email.

The victim sees only a page flash by, or nothing. With a GET request the attack is even simpler, because a link or even an <img src="…"> tag will send it, which is why a state-changing action must never use GET.

Burp Suite, a common testing tool, can generate this kind of proof-of-concept page automatically from a captured request.


4. What CSRF can and cannot do

CSRF can CSRF cannot
Make the victim's browser send requests that change state: change settings, transfer funds, post content, delete data Read the response. The same-origin policy stops the attacker's page from reading what the target site returns
Work against any action that needs only the cookie Perform actions that need a secret value the attacker does not have
Work without any flaw in the page itself Change a logged-in user's data when the victim is not logged in to the target site (the cookie is the whole point). The exception is login CSRF, below

So CSRF is about actions, not stolen data. That is also the key difference from XSS:

CSRF XSS
The attacker's code runs On another site, which sends a request to the target Inside the target site
Can read data from the target No Yes
Typical result An unwanted action Full control of what the victim does on the site, including reading their data
Does a CSRF token stop it? Yes No: an XSS script can read the token and use it, so XSS can defeat CSRF protection

Login CSRF

A login form can be forged too. Login CSRF makes the victim's browser log in to a site as the attacker, using the attacker's own account. OWASP explains that people sometimes skip login forms, assuming CSRF does not apply because the "user is not authenticated at that stage," but that "CSRF vulnerabilities can still occur on login forms where the user is not authenticated, but the impact and risk is different." Its example: the victim then enters a credit card on a shopping site while signed in to the attacker's account, and the attacker may later use the stored card details.

The defence is the same idea applied earlier: OWASP says login CSRF "can be mitigated by creating pre-sessions (sessions before a user is authenticated) and including tokens in login form," and that the pre-session must be destroyed and replaced by a new session after login to avoid session fixation.


5. How to prevent CSRF

OWASP's cheat sheet gives this order of preference: first, check whether your framework has built-in CSRF protection and use it; otherwise add CSRF tokens to all state-changing requests and validate them on the server; modern browsers also let you rely on Fetch Metadata headers (with fallbacks); and SameSite cookies, Origin and Referer checks and extra user interaction are layers of defence in depth.

1. CSRF tokens (the main defence)

A CSRF token is a unique, secret and unpredictable value generated by the server and shared with the client, in the words of PortSwigger. The server puts it into every form (or sends it to the page's JavaScript) and requires it on every state-changing request. A cross-site attacker cannot read the page that holds the token, so they cannot include it, and the forged request fails. This breaks the third condition: now there is an unpredictable parameter.

<form action="/account/email" method="POST">
  <input type="hidden" name="csrf_token" value="b6c1…e9">
  <input name="email">
</form>

Rules for a token to work:

Rule Why
Unpredictable (from a secure random generator) Otherwise the attacker guesses it
Tied to the user's session A token valid for anyone is a token the attacker can fetch with their own account
Checked on every state-changing request, including APIs A missing check on one endpoint is an open door
Rejected if missing, not only if wrong Otherwise the attacker simply leaves it out
Compared carefully and never placed in the URL URLs leak into logs and the Referer header

Many web frameworks have this built in; OWASP's cheat sheet lists .NET, Angular, Spring Security, Ruby on Rails, Laravel and Django among them. Use the framework's version rather than writing your own, and do not switch it off just to make something work.

2. Fetch Metadata (Sec-Fetch-Site)

Modern browsers add headers to every request that describe where it came from. The most useful is Sec-Fetch-Site, with the values same-origin, same-site (a different origin on the same site, such as a sibling subdomain), cross-site and none (typed in the address bar, a bookmark, or opened from another program). web.dev describes a resource isolation policy built on it: allow requests that are same-origin, same-site or browser-initiated, plus simple top-level GET navigations (which is how a user clicking a link to your site arrives), and reject other cross-site requests, except for endpoints that are meant to be used cross-origin. Because the Sec- prefix means page scripts cannot set or change these headers, they are a strong signal that needs no token. Two cautions: the headers are sent by modern browsers only (web.dev lists Chrome 76, Firefox 90, Safari 16.4 and Edge 79 and later), so a policy must decide what to do when they are missing, and same-site includes sibling subdomains, so sensitive endpoints may want to allow only same-origin.

3. SameSite cookies

The SameSite attribute tells the browser when to send a cookie on requests that start from another site. MDN lists three values:

Value Behaviour
Strict Sent only for requests that start on the cookie's own site
Lax Like Strict, but also sent when the user navigates to the site from elsewhere (for example by clicking a link)
None Sent on cross-site requests too. Must be combined with Secure

If no SameSite attribute is set, modern browsers treat the cookie as Lax by default, as MDN notes, so a cross-site form POST generally will not carry the cookie (browsers differ in the details). This breaks the second condition and has made classic CSRF much harder.

Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Lax

OWASP calls SameSite useful as a defence-in-depth control that does not replace a proper CSRF defence in most deployments. Why it is a layer and not the whole answer:

  • "Same site" is not "same origin." A site means the registrable domain, so blog.example.com and shop.example.com count as the same site (web.dev's example is www and login subdomains: cross-origin but same-site). OWASP warns that a vulnerability on any sibling host can issue requests the browser treats as same-site.
  • Lax allows top-level GET navigations, so an action that changes state on a GET request is still exposed. OWASP says plainly that if any state-changing operation is reachable by GET, SameSite=Lax will not stop it.
  • Behaviour differs across browsers and versions, and cookies set with SameSite=None are fully exposed.
  • Do not depend on the default: set the attribute explicitly.

4. Origin and Referer validation

The browser sends an Origin header (and often Referer) saying which site produced the request. The server can check that it is its own. PortSwigger rates the Referer check as generally less effective than token validation, because the header can be missing or stripped and applications handle that case inconsistently. Use it as a supporting check.

5. Other good habits

Habit Why
Never change state with GET Links and images would be enough to attack
Ask for the current password or a second factor for sensitive actions Adds an unpredictable value the attacker cannot supply
Custom headers or JSON for APIs, with a strict CORS policy A cross-site page cannot add a custom header without the server's permission via CORS, but a loose CORS configuration removes that protection
Short sessions and re-authentication for high-risk changes Limits the time a forged request can work
Fix XSS first Any XSS defeats CSRF defences, so both must be handled

6. How testers find it

With permission:

  1. List the state-changing requests (change email, change password, transfer, delete, add user).
  2. Check whether a token is present, and whether it is really validated: remove it, change it, leave it empty, or submit a token that was issued to a different account or session. A server that accepts any of these has a real flaw. Reusing the same token again within the same session is not a flaw by itself: OWASP says tokens "should be generated only once per user session or each request," and per-request tokens are stronger but not required for a token to count as protection.
  3. Include the login form, and check whether it has a token or other protection too.
  4. Check the cookie's SameSite attribute in the browser's developer tools.
  5. Try the same action with GET, or with another HTTP method.
  6. Build a proof-of-concept page on a different origin and see whether the action happens while logged in.

Practise on PortSwigger Web Security Academy: CSRF, which has labs for each of these mistakes.


7. Common mistakes

Myth The facts
"POST requests are safe from CSRF" The example above is a POST. Any method can be forged by a form or script
"HttpOnly cookies prevent CSRF" HttpOnly stops scripts from reading the cookie. The browser still sends it
"HTTPS stops CSRF" HTTPS protects the connection, not the intent of the request
"SameSite makes tokens unnecessary" It is a strong extra layer. Sibling subdomains, GET navigations and older browsers keep tokens relevant
"CORS protects me" CORS controls who can read responses, not whether a request is sent. A simple form POST needs no CORS permission
"Only banks need it" Any site with logged-in actions does: settings, social posts, admin panels, routers, internal tools
"A secret in the cookie is a CSRF token" A value that the browser sends automatically is no use as proof, because the attacker's forged request carries it too. A token must be added by the page itself
"My site has XSS protection, so I am done" They are different flaws with different fixes

Closing

CSRF works because browsers attach cookies to a site's requests automatically, whoever started them. An attacker's page can therefore make your logged-in browser send an action you never intended, without seeing your cookie and without reading the result. It needs a relevant action, cookie-only authentication and predictable parameters. The defences take those away: unpredictable per-session tokens, SameSite cookies, Fetch Metadata and Origin checks, and never changing state with GET.

Keep these points:

  • The browser sends the cookie for you, which is what the attacker abuses.
  • Three conditions: a relevant action, cookie-only session handling, no unpredictable parameters.
  • CSRF performs actions but cannot read responses; XSS can do both.
  • Use your framework's built-in protection or CSRF tokens first; Fetch Metadata, SameSite and Origin checks add layers.
  • Never use GET to change state.
  • XSS defeats CSRF protection, so fix both.