CSRF Attack Explained How Request Forgery Works
A CSRF attack (crosssite request forgery) forces a victim browser to send an unwanted, statechanging request to a website where the victim is already logged in. The browser attaches the session cookie automatically, so the server cannot tell the forged request from a genuine one. AntiCSRF tokens, SameSite cookies and origin checks stop it.Imagine you are logged in to your online banking in one browser tab. In another tab, you open a harmless looking page. Without any click on a suspicious button, that page quietly instructs your browser to submit a transfer form to your bank. The bank sees a valid session cookie, accepts the request and the money moves. You never approved anything. This is the essence of a CSRF attack and it remains one of the most instructive examples of how trust between browsers and servers can be abused.This guide explains the CSRF vulnerability from first principles. You will learn what a CSRF attack is, why it works, what conditions must be true for an application to be exposed and how defenders reason about it. If you are new to the broader landscape, our overview of web application security threats shows where request forgery sits among other risks.
What Is a CSRF Attack?
Cross site request forgery is a browser based attack in which a malicious site, email, or script causes a victim browser to issue an unauthorized HTTP request to a different site where the victim is authenticated. The attacker does not steal the session. Instead, the attacker borrows it for a single action.The word forgery is precise. The request is crafted by the attacker, but it travels from the victim own browser, carrying the victim's own credentials. From the server perspective, nothing looks wrong, the cookie is valid, the user is logged in and the endpoint accepts the parameters. The attack succeeds because the application confirms who is sending the request but never confirms that the user actually intended to send it.A deeper walkthrough of the same topic is available in our dedicated CSRF attack article, which makes a good companion to this explanation.
Why Browsers Make CSRF Possible
To understand why this class of session based attacks exists, you need to understand how browsers handle cookies. When you log in, the server typically sets a session cookie. From then on, the browser attaches that cookie to every request sent to that site, regardless of which page or origin triggered the request. Security researchers call these ambient authority credentials that travel automatically, without the page code having to supply them.
That design is convenient. It lets images, forms and scripts from anywhere on the web point at your account on another site and still work. It is also the root of the problem. If an attacker page can cause the browser to send a request to your bank, the browser will helpfully include your bank cookie.Cookie based authentication is therefore the common denominator in nearly every CSRF security vulnerability. Applications that authenticate each request with a header the browser does not add by itself, such as a bearer token stored in script memory and attached manually, are far less exposed, because a forged crosssite request cannot attach that header.
How CrossSite Request Forgery Works, Step by Step
The flow below is the standard model of how crosssite request forgery works.
-
The victim authenticates. The user logs in to a legitimate application and the browser stores a session cookie.
-
The attacker prepares a trap. The attacker builds a page, an email, or an injected snippet containing a request aimed at a sensitive endpoint, such as changing an email address.
-
The victim visits the trap. This can happen through a link, an advertisement, a forum post, or a message. The victim stays logged in to the target site in the background.
-
The browser sends the forged request. The trap triggers the request automatically, for example by autosubmitting a hidden form.
-
The browser adds the cookie. Because the destination is the target site, the browser attaches the session cookie.
-
The server processes the request. With no way to distinguish it from a legitimate action, the server performs the change.
A minimal example makes this concrete. Suppose an application changes an account email with this request
When a logged in victim loads that page, the email on the account changes. The attacker can then use the password reset feature to take over the account entirely. A single forged request became a full compromise.
The Three Conditions for a CSRF Vulnerability
A CSRF vulnerability requires three things to be true at once. Understanding them helps both attackers reason about targets and defenders reason about fixes.
A relevant action exists. The application must offer something worth forging, such as changing a password, updating contact details, transferring funds, or granting permissions.
Cookie based session handling is used. The application relies only on cookies, or other automatically attached credentials, to identify the user.
No unpredictable request parameters exist. The attacker must be able to determine or guess every value the request needs. If a secret value is required and the attacker cannot know it, the forgery fails. This is exactly the idea behind antiCSRF tokens.Remove any one of these conditions and the attack collapses. Most prevention techniques work by removing the third.
State Changing Requests What Attackers Target
Not every request is interesting to an attacker. A request that only reads data is usually harmless in a CSRF context, because the attacker cannot see the response; the browser sameorigin policy prevents the attacker page from reading content returned by another origin. What matters are statechanging requests, which modify data or permissions on the server.
Common targets include
-
Changing the account email address or phone number
-
Updating a password without requiring the old one
-
Transferring money or changing payout details
-
Adding a new administrator or changing a user role
-
Deleting records, posts, or entire accounts
-
Changing security settings, such as disabling multifactor authentication
-
Creating API keys or authorizing third party applications
A useful design discipline is to list every statechanging endpoint in your application and ask a simple question about each: what proves that this specific user meant to do this? If the answer is only the cookie was present, you have found a candidate for abuse.
GET, POST and JSON Does the Method Matter?
A persistent myth says that switching sensitive actions from GET to POST prevents CSRF. It does not. It only makes the exploit slightly longer to write.
GET requests are the easiest to forge. An image tag such as <img src=https//app.example.com/delete?id=7> triggers a GET request the moment the page loads. This is why statechanging actions must never be exposed through GET. Beyond security, it violates HTTP semantics, since GET is meant to be safe and repeatable.
POST requests can be forged with autosubmitting forms, as shown earlier. Browsers allow crosssite form submissions by default, so a POST endpoint that accepts formencoded data is fully exposed without further protection.
JSON requests are trickier. A plain crosssite form cannot set the content type to application/json and a crossorigin fetch with that content type triggers a CORS preflight that the target server must approve. However, applications that parse JSON bodies regardless of the declared content type can still be reached with text/plain forms or similarly crafted submissions. We never use JSON as a defense on its own.
CSRF vs XSS vs Clickjacking
Beginners often confuse request forgery with other browser based attacks. The table below separates them.
|
Attribute |
CSRF |
XSS |
Clickjacking |
|
Core idea |
Forges requests using the victim session |
Runs attacker script inside the trusted site |
Tricks the user into clicking a hidden element |
|
Where attacker code runs |
On the attacker page |
Inside the vulnerable site |
On the attacker page, framing the target |
|
Can read responses |
No |
Yes |
No |
|
Needs user session |
Yes |
Not always |
Yes |
|
Main fix |
Tokens, SameSite, origin checks |
Output encoding, CSP |
Frameancestors, XFrameOptions |
The relationship matters in practice. A crosssite scripting flaw can defeat CSRF tokens entirely, because injected script can read the token from the page and submit it. That is why a mature defense treats these issues together and why the broader OWASP Top 10 is worth studying as a connected set rather than a checklist of isolated items.
The Impact of a CSRF Attack
The damage depends on the privileges of the victim. Against an ordinary user, an attacker may change profile data, post content, or move funds. Against an administrator, a single forged request can create a new privileged account, change application configuration, or disable protections.
Several factors raise the severity
-
Privilege of the victim. Admin accounts turn a minor flaw into a critical one.
-
Chaining with other bugs. A forged email change plus password reset equals account takeover.
-
Scale. An attacker who embeds a forged request in a popular page can hit thousands of loggedin users at once.
-
Stealth. Because the request comes from the real browser, logs show normal looking activity from the real IP address.
Business consequences include financial loss, data tampering, reputational damage and compliance exposure, especially for applications that handle regulated data.
How to Recognize a CSRF Security Vulnerability
Developers and testers can spot likely exposure with a few quick observations.First, inspect a sensitive request in the browser developer tools. Look for a parameter that looks like a random token, often named csrf, _token, or authenticity_token. If none exists and the request relies solely on a cookie, the endpoint is suspect.
Second, check the cookie attributes. A session cookie without a SameSite attribute, or with SameSite=None, will be sent on crosssite requests. Modern browsers apply a default of Lax when no attribute is specified, which blocks many crosssite POSTs, but relying on browser defaults is fragile and does not cover every browser or every scenario.Third, test whether the server validates the token at all. Remove it, change one character, or substitute a token from another account. Some applications generate tokens but never verify them, which is functionally the same as having none.
For handson practice with the testing side of this process, our guide to SQL injection testing demonstrates the same mindset of probing inputs and observing server behavior.
Core Defenses at a Glance
The full toolkit is covered in other guides, but every learner should know the headline defenses.
AntiCSRF tokens. The server issues an unpredictable, persession or perrequest value and requires it on every statechanging request. The attacker page cannot read or guess it. The two classic implementations are the synchronizer token pattern and the double submit cookie pattern.
SameSite cookies. Setting SameSite=Lax or SameSite=Strict on the session cookie instructs the browser not to send it on most crosssite requests. This is a strong second layer, though not a complete replacement for tokens.
Origin and Referer validation. The server checks that the Origin header, or failing that the Referer, matches the expected site for statechanging requests.
Reauthentication for sensitive actions. Asking for the current password or a onetime code before highrisk changes ensures that a forged request cannot complete on its own.
Fetch Metadata headers. Headers such as SecFetchSite let servers reject requests that originate from other sites.No single control is perfect. Layering them is what makes request forgery impractical. These measures also belong in your general web security best practices baseline, alongside input validation and secure session management.
Building CSRF Awareness Into Development
Because the flaw is a design gap rather than a coding typo, it is best addressed through process. Teams that handle it well tend to share a few habits.
They adopt a framework that provides CSRF protection by default and avoid disabling it for convenience. Many popular frameworks include middleware that issues and verifies tokens automatically; the risk usually appears when developers exempt an endpoint and forget about it.
They include request forgery in code reviews. A reviewer looking at a new endpoint should ask whether it changes state, how the user is authenticated and what stops a crosssite caller. Our secure code review guide offers a practical checklist for building that habit.
They test continuously. Automated scanners catch missing tokens, but manual testing is needed to find logic gaps, such as tokens that are not tied to the user session or endpoints that accept both POST and GET.
Finally, they treat security as part of everyday engineering rather than a final gate. The principles in a broader secure development approach apply directly secure defaults, least privilege and verification at every layer.
Conclusion
A CSRF attack exploits a simple fact: browsers send cookies automatically and servers often accept them as proof of intent. The attacker never needs your password. They only need you to be logged in and to load a page they control. The result can range from an annoying setting change to a full account takeover.The encouraging news is that the problem is well understood and solvable. AntiCSRF tokens, SameSite cookies, origin checks and reauthentication each close a different gap and together they make forgery impractical.
Start by inventorying your statechanging endpoints, confirm each one is protected and then test the protection rather than assuming it works.To keep building practical skills, explore handson training and challenges at AppSecMaster, where you can move from understanding these concepts to exploiting and fixing them yourself. Many vulnerabilities in the wild also stem from unsafe input handling, so reading about defending against injection attacks is a natural next step.
Frequently Asked Questions (FAQs)
What is a CSRF attack in simple terms?
A CSRF attack makes your browser perform an action on a site you are logged in to, without your knowledge. The attacker page triggers the request and your browser adds your login cookie automatically, so the site believes you made the request yourself.
How does crosssite request forgery work?
The victim logs in to a target site, then visits an attacker controlled page. That page sends a hidden request, usually through an autosubmitting form, to the target. The browser attaches the session cookie and the server processes the statechanging request as though the user had intended it.
Can a CSRF attack steal data?
Generally no. The attacker cannot read the response because of the same origin policy. The goal is to change state, such as altering an email address, transferring funds, or changing permissions. Those changes can still lead to data exposure indirectly, such as through account takeover.
Does HTTPS prevent CSRF?
No. HTTPS encrypts traffic but does nothing to verify user intent. A forged request sent over HTTPS is still accepted if the cookie is valid and no token or origin check exists. You need dedicated CSRF defenses in addition to HTTPS.
What is the best way to prevent CSRF attacks?
Use a layered approach antiCSRF tokens on all statechanging requests, SameSite cookie attributes, origin validation and reauthentication for sensitive operations. Never use GET for actions that change data and keep framework protections enabled.
- Art
- Causes
- Crafts
- Dance
- Drinks
- Film
- Fitness
- Food
- Spellen
- Gardening
- Health
- Home
- Literature
- Music
- Networking
- Other
- Party
- Religion
- Shopping
- Sports
- Theater
- Wellness