Skip to content
Knowledge base Updated: February 5, 2026

What Is CSRF (Cross-Site Request Forgery)? Detection, How It Works, and Prevention

A CSRF attack forces users to unknowingly perform actions in your application. Our guide explains how to detect this vulnerability, how anti-CSRF tokens work, and how an nFlo audit can help you eliminate it.

In the complex world of web application security, there are attacks that are insidious in their simplicity. They don’t rely on password cracking or complex cryptanalysis, but on cleverly exploiting the trust that the browser places in the logged-in user. One of the most classic and yet still dangerous examples of such an attack is CSRF, or Cross-Site Request Forgery. This is an attack in which a victim, who has an active session in your application, is induced to unknowingly perform an unwanted action.

Imagine that your customer, logged into his online store’s dashboard, accesses a malicious site that changes the delivery address for all new orders in the background, without his knowledge. That’s what CSRF is in practice - a silent, invisible attack that uses the victim’s credentials to achieve the criminal’s goals. In this guide, we will explain in detail how this mechanism works, what risks it poses, and most importantly - what are the effective and modern defense methods that every developer and owner of a web application must know and use.

Shortcuts

What is a CSRF (Cross-Site Request Forgery) attack and why is it so dangerous?

CSRF, or Cross-Site Request Forgery, is a type of attack on a web application in which an attacker forces the browser of an authenticated (logged-in) user to send a crafted, unsolicited request to a vulnerable application. The application, receiving such a request, treats it as fully authentic because it comes from the user’s browser, which has an active, valid session (e.g., based on a cookie). As a result, the victim unknowingly performs the action the attacker has prepared for it.

The danger of a CSRF attack lies in its insidiousness and exploitation of trust. This attack does not steal a password or take over a user’s session. Instead, it exploits the victim’s already existing, active session. The hacker doesn’t need to know the login credentials - it’s enough that the victim is logged into the vulnerable service at the time of the attack, and their browser automatically attaches the appropriate session cookies to the fake request, authenticating them in the eyes of the server.

The attack is dangerous because it can involve any action that a logged-in user can perform in the application. It could be changing an email address or account password, making a bank transfer, deleting data, publishing a compromising social media post on behalf of the victim, or changing configuration settings on a company system. The consequences can be catastrophic, both for the individual user (financial loss, loss of control over the account) and for the entire company (change of privileges, sabotage, data leakage).

📚 Read the complete guide: IAM / Zero Trust: Identity and access management - from the basics to Zero Trust

What is the mechanism of the attack, in which the victim unknowingly performs unwanted actions?

The CSRF attack mechanism is based on a simple but ingenious exploitation of the fundamental way web browsers and cookie-based authentication sessions work. The process can be broken down into several steps.

Step 1: The victim logs into the vulnerable application. The user goes to https://bank-ofiary.com and logs into their account. The bank’s server creates a session and sends a session cookie to the browser, which will be automatically included in all future requests to the bank-of-victims.com domain.

Step 2: The attacker prepares a malicious site. The hacker creates his own website, such as https://zlosliwa-strona.com. On this page he places an HTML element invisible to the user, which will automatically send a request to the bank’s server. For example, it can be a hidden form or an image whose source (src) points to a URL that performs a specific action, e.g. https://bank-ofiary.com/przelej?odbiorca=haker&kwota=10000.

Step 3: The victim accesses the malicious site. The hacker, using social engineering techniques (e.g., by sending a link in a phishing email), persuades the victim to visit his malicious site. The user, who still has an open and active session at his bank in the background, goes to https://zlosliwa-strona.com.

Step 4: The browser unknowingly sends a fake request. When the malicious page loads, the victim’s browser encounters a hidden element and automatically sends a POST or GET request to https://bank-ofiary.com/przelej… Most importantly, since the request is directed to the bank-of-victim.com domain, the browser, according to its standard operation, automatically attaches a session cookie belonging to that domain.

Step 5: The server performs the action. The bank’s server receives a transfer request. It sees that the request contains a valid active session cookie, so it treats it as a fully authentic request coming from a logged-in user. If the application doesn’t have additional CSRF protection, the server processes the request and performs the transfer to the hacker’s account. The victim has no idea about anything until he checks his account balance.

What are typical examples of CSRF attacks (e.g., password change, bank transfer)?

Vulnerability to CSRF attacks can apply to any action in a web application that modifies server-side state and relies solely on session authentication. The impact of the attack depends on what functions the vulnerable application provides.

One of the most classic and dangerous examples is an unauthorized bank transfer or change of data in the financial system. As described in the previous section, an attacker can prepare a page that orders a transfer from a logged-in victim’s account to his own account in the background. Similarly, in a company’s accounting system, an attacker can force the browser of a logged-in employee to change the bank account number of one of the contractors, causing future payments to go to the fraudster.

Another popular target is user account management functions. A CSRF attack can be used to change the email address associated with the victim’s account. After a successful change, the attacker can use the “forgot password” feature to take full control of the account. Similarly, it is possible to launch an attack that will change the victim’s password to a password known to the attacker if the password change function only requires a new password, without verifying the old one.

Other examples include a wide range of activities, such as:

  • Publishing content on behalf of the victim on social networks or forums (e.g., compromising posts, spam).

  • Adding products to the shopping cart or placing orders in the online store for the victim’s account.

  • Change user privileges in the administrative system.

  • Deleting data, such as deleting all emails from the victim’s account or deleting their account on the site.

How to distinguish between a CSRF vulnerability and an XSS (Cross-Site Scripting) attack?

CSRF and XSS (Cross-Site Scripting) are two very common and dangerous vulnerabilities in web applications, but they work in very different ways and use different attack vectors. The key difference lies in who is targeted and where the trust is placed.

In a CSRF attack, the target is the application server. The attacker takes advantage of the trust the server has in the browser of the logged-in user. The hacker forces the victim’s browser to send a full-fledged, authenticated request to the server to perform some action. Here, the user is just an unwitting intermediary, and his browser is a tool in the attacker’s hand.

In an XSS attack, the target is another user’s web browser. The attacker takes advantage of the user’s trust in the vulnerable website. The hacker “injects” malicious JavaScript into the content of the page (e.g., through a comment field). When another user (the victim) opens that page, his browser, trusting the page, executes the malicious script. This script, running in the context of a trusted domain, can steal the victim’s cookies, modify the page’s appearance or perform actions on behalf of the victim.

Simply put: CSRF is forcing your browser to do something on a site you are logged into. XSS is executing malicious code from a trusted site in your browser. Both attacks are dangerous, but require completely different defense mechanisms.

How can developers detect and test their applications for CSRF vulnerabilities?

Detecting CSRF vulnerabilities requires a combination of code analysis, manual testing and the use of automated tools. The goal is to find all points in the application that perform state-modifying actions (e.g., changing data, deleting something) and verify that they are adequately protected against fraudulent requests from other domains.

The first step is a manual analysis of the code and application (code review). The developer or security tester should identify all HTTP requests that lead to data changes - that is, mainly POST, PUT, DELETE requests, but also GET requests that have side effects (which is a bad practice in itself). For each such endpoint (endpoint), verify that the authentication mechanism is based solely on session cookies and that any additional security, such as an anti-CSRF token, is implemented.

Manual testing usually uses proxy tools such as Burp Suite or OWASP ZAP. The tester intercepts a valid request sent by the application (e.g., a password change request). Then, it removes the anti-CSRF token (if any) from it and tries to send it again. If the server accepts such a request, it indicates the existence of a vulnerability. The tools also allow automatic generation of a “proof of attack” (Proof of Concept) in the form of an HTML page that can be opened in a browser to see if the attack actually works.

Continuous Integration and Delivery (CI/CD) can also use automated application security scanners (DAST - Dynamic Application Security Testing). These tools automatically scan an application in an attempt to detect common vulnerabilities, including lack of CSRF protection. While not as precise as manual tests, they provide an important additional layer of verification.

What is the most effective method of defense, the anti-CSRF tokens (anti-CSRF tokens)?

The most widespread and effective method of defense against CSRF attacks is a mechanism based on anti-CSRF tokens, also known as “synchronizer tokens.” The idea behind this protection is simple: every request that modifies the state of an application must be accompanied by an additional, unique and unpredictable “secret” that only the server and the legitimate user’s browser know.

The process works as follows:

  • When a user logs into the application or simply loads a page with a form, the server generates a random string unique to the session - an anti-CSRF token.

  • This token is placed in two places: it is stored in the user’s server-side session and it is embedded directly in the HTML code of the form, most often as a hidden field ().

  • When a user fills out and submits a form, the browser sends both the form data and the hidden anti-CSRF token to the server.

  • The server, upon receiving the request, performs a key verification: it compares the token received in the form with the token stored in the user’s session. If the two tokens are identical, the server considers the request authentic and processes it. If the tokens are missing or different, the server rejects the request as a potential CSRF attack attempt.

Why is this effective? An attacker, creating a malicious page, is unable to know or guess the value of the unique token that was generated for the victim’s session and embedded in the original form. The Same-Origin Policy prevents a script from a malicious domain from reading the content of a page from a legitimate domain. As a result, a fake request sent by an attacker will not contain a valid token, and thus will be rejected by the server.

How do other defenses work, such as the SameSite attribute for cookies?

In addition to anti-CSRF tokens, modern browsers have introduced additional defense mechanisms that make it significantly more difficult to launch attacks of this type. The most important of these is the SameSite attribute for cookies, which allows you to control if and when cookies should be sent in inter-domain requests.

The SameSite attribute can take three values:

  • Strict: This is the safest setting. The browser will never send a cookie in a request coming from another domain. This means that if a user clicks on a link to our application from an external site, they will not be automatically logged in. This fully protects against CSRF attacks, but may be impractical from a usability perspective.

  • Lax: This setting is now the default in most browsers. The browser will only send a cookie in a cross-domain request if it is a GET request and it is top-level navigation (the user clicks on a link). Cookies will not be sent in POST type requests, nor in requests initiated in the background (such as through images or iframes). This provides good protection against most common CSRF attacks.

  • None: This setting restores the old behavior - the cookie is sent in all requests, including inter-domain requests. To use this value, the Secure attribute (requiring HTTPS) must also be set. This is necessary in some scenarios of integration between different sites, but requires other methods of defense against CSRF.

Another defense mechanism, though of narrower use, is server-side verification of the Referer or Origin header. The server can check what site the request came from and accept only those from its own domain. However, this method has some disadvantages - the Referer header may be absent or forged, and the Origin header is not sent in all cases. Therefore, these methods are at most an additional layer of defense, not the main security.

What are the best coding practices that minimize the risk of this vulnerability?

Minimizing CSRF risk requires developers to adopt a set of best practices and secure coding principles that should be applied throughout the application lifecycle.

1. use a secure framework: the most important rule is to use a modern web framework (e.g. Django, Ruby on Rails, Laravel, ASP.NET Core) that has CSRF protection mechanisms built in and enabled by default (as discussed in the next section). Re-implementing these protections from scratch is risky and error-prone.

(2) Never use GET method for state-modifying actions: GET type requests should be used only for retrieving data. Any action that changes, creates or deletes anything in the application (e.g. “delete account”, “change password”, “add to cart”) must be performed using POST, PUT, PATCH or DELETE methods. It is extremely dangerous to use GET for such operations, as it makes it easy to launch a CSRF attack (e.g., using a simple link in an email or a ) tag.

3 Always implement token-based protection: Even if you use SameSite attribute, always implement anti-CSRF token-based protection as your main line of defense. This is the most reliable method. Make sure the tokens are generated securely at random, are associated with the user’s session, and are properly verified on the server side for each request that modifies the state.

4 Require re-authentication for critical operations: For particularly sensitive actions, such as changing a password or email address or authorizing a large financial transaction, it is a good practice to require the user to re-authenticate. This provides an additional, powerful layer of protection that will stop a CSRF attack even if other mechanisms fail.

Do web frameworks (e.g. Django, Ruby on Rails) offer built-in protection against CSRF?

Yes, and this is one of the biggest advantages of using modern, mature web frameworks. Virtually all popular frameworks, such as Django (Python), Ruby on Rails (Ruby), Laravel (PHP), ASP.NET Core (C#) or Spring (Java), offer built-in and, most importantly, default-enabled protection mechanisms against CSRF attacks. The developers of these tools are well aware of the seriousness of this vulnerability and have built proven, developer-transparent protections into their products.

These mechanisms typically rely on anti-CSRF tokens. The framework automatically generates the token when a session is created, and then ensures that it is added as a hidden field to every form generated using the built-in tools. When the form is submitted, the framework automatically intercepts the request, verifies the validity of the token, and if everything matches, passes it on for further processing. If the token is missing or invalid, the request is automatically rejected with an error.

As a result, a developer, using the standard components of the framework, often doesn’t even have to remember to implement CSRF protection - it just works “under the hood.” However, it is crucial not to disable these mechanisms globally (which, unfortunately, developers sometimes do, running into problems) and to understand when they may not work. For example, for requests sent via JavaScript (AJAX), the developer must manually ensure that the anti-CSRF token is retrieved from the page and included in the headers of such a dynamic request.

Using a framework that takes care of security for us is one of the best practices. It frees developers from having to “reinvent the wheel” and implement their own potentially flawed cryptographic mechanisms, allowing them to focus on the business logic of the application.

What is the importance of proper configuration of HTTP headers in CSRF prevention?

Although the main line of defense against CSRF is tokens, the correct configuration of HTTP headers sent by the application server can provide an important additional layer of protection that makes some variants of the attack difficult or impossible. This is especially true for headers related to CORS policies and cookies.

As mentioned earlier, the Set-Cookie header and its SameSite attribute are crucial. Setting this attribute to Lax (which is the default in many browsers today) or Strict is a powerful CSRF mitigation mechanism. It prevents the browser from automatically sending session cookies in inter-domain POST requests, which blocks the classic CSRF attack vector. Proper configuration of this attribute should be standard for all session cookies.

Proper configuration of CORS (Cross-Origin Resource Sharing) headers is also of some importance. Although CORS and CSRF are different problems, a liberal CORS policy can make it easier to launch more complex attacks. In particular, if an API server is misconfigured to accept requests from any domain (Access-Control-Allow-Origin: *) and at the same time allows credentials to be sent, this can open up new opportunities for an attacker. Therefore, CORS policy should always be as restrictive as possible, allowing access only to trusted, specifically defined domains.

Other security headers, while not directly protecting against CSRF, contribute to the overall hardening of the application. For example, Content-Security-Policy (CSP) can limit the ability to execute malicious scripts, which is important in the context of defending against XSS, which can sometimes be used to bypass anti-CSRF protections.

How can end-users partially protect themselves from the effects of attacks of this type?

While the primary responsibility for protecting against CSRF rests with developers and application owners, end users can also take certain steps to minimize the risk and potential impact of an attack. These steps are based on good habits and digital hygiene.

The most important and simple rule of thumb is to regularly log out of online services when you’re done, especially those that give you access to sensitive data or functions (online banking, email, corporate systems). A CSRF attack is only effective if the victim has an active session on the vulnerable service. If we are logged out, the fake request sent by the malicious site will not be authenticated and the server will reject it.

Another good habit is to avoid browsing the Internet from accounts with high privileges. Don’t surf the web unnecessarily while logged into an administrator account on a company system or an account with financial transaction privileges. For casual browsing, it’s a good idea to use an account with lower privileges or simply log out.

Users should also exercise general vigilance and common sense. Avoid clicking on suspicious links received in emails or on instant messaging, and avoid visiting websites with questionable reputations, especially while logged into important services. Regularly clearing cookies and browser history can also make attacks more difficult to some extent. However, it is important to remember that these are only ancillary measures, and the fundamental security must be provided by the application itself.

How does nFlo’s web application penetration testing help detect and eliminate critical vulnerabilities such as CSRF?

At nFlo, we fully understand that even with the best frameworks and coding practices, subtle configuration or logic errors can occur in complex web applications, leading to critical vulnerabilities such as CSRF. That’s why we offer professional web application penetration testing that simulates the actions of a real hacker to identify and verify such vulnerabilities before they are exploited by criminals.

Our certified security testers approach each application in a methodical manner, combining automated scanning with advanced manual testing techniques. In the context of CSRF, our experts systematically identify all endpoints in an application that perform state modification actions. Then, for each of them, they run a series of tests to verify that the defense mechanisms are implemented correctly and cannot be circumvented.

In practice, we intercept valid requests and then try to modify them, for example, by removing or falsifying the anti-CSRF token. We verify that the server correctly rejects such manipulated requests. We also verify that the tokens are generated in a securely random manner and that they are properly validated within the user session. We test various attack vectors, including those using GET requests, and check how the application behaves with different content types (Content-Type).

The result of our testing is a detailed and easy-to-understand report that not only lists the vulnerabilities found and assesses their risk level (e.g., critical, high), but also provides precise, technical recommendations for fixing them. We provide developers with specific guidance on how to fix code and configure security to fully eliminate the risk. When you invest in nFlo penetration testing, you get peace of mind that your application has been checked by experts, and your users are protected from insidious attacks such as CSRF.


Why this vulnerability survives in modern applications

CSRF is supposed to be a solved problem: frameworks ship token protection, and modern browsers default cookies to a stricter SameSite policy. It survives anyway, in the places the framework does not cover — an endpoint added by hand, an API that accepts a simple content type, a legacy path kept alive for one integration, or a subdomain that shares cookies with the main application. Those are exactly the paths a scanner reports and a developer dismisses as a false positive.

Confirming whether such a path is genuinely exploitable is what a scoped web application penetration test establishes.

Learn key terms related to this article in our cybersecurity glossary:


Learn More

Explore related articles in our knowledge base:


Explore Our Services

Need cybersecurity support? Check out:


Frequently asked questions

What is a CSRF vulnerability and how does it work?

Cross-Site Request Forgery (CSRF) is a vulnerability that tricks an authenticated user into unknowingly submitting malicious requests to a web application. The attacker crafts a request that the victim's browser automatically sends with their valid session credentials, causing actions such as fund transfers or account changes to be performed without the user's knowledge.

How can developers detect CSRF vulnerabilities in their applications?

Developers can detect CSRF vulnerabilities through manual code review looking for state-changing requests that lack token validation, automated security scanning tools such as OWASP ZAP, and professional penetration tests that specifically target CSRF weaknesses. Testing all forms and AJAX requests that modify server-side state is essential.

What is an anti-CSRF token and how does it prevent attacks?

An anti-CSRF token is a unique, unpredictable value generated by the server and embedded in forms or request headers. When a request is submitted, the server validates that the token matches the expected value for that session. Because an attacker cannot obtain this token from a different origin, forged requests will fail validation.

What other measures can organizations take to prevent CSRF attacks?

In addition to anti-CSRF tokens, organizations can implement the SameSite cookie attribute to restrict cross-origin cookie sending, use the Origin and Referer headers for validation, require re-authentication for sensitive actions, and regularly audit their web applications through security testing. Defense in depth using multiple complementary controls provides the strongest protection.

Share:

Talk to an expert

Have questions about this topic? Get in touch with our specialist.

Sales Representative
Łukasz Gil

Łukasz Gil

Sales Representative

Response within 24 hours
Free consultation
Individual approach

Providing your phone number will speed up contact.

Want to Reduce IT Risk and Costs?

Book a free consultation - we respond within 24h

Response in 24h Free quote No obligations