PreEmptive logo

Cross-Site Request Forgery (CSRF): What It Is and How to Prevent It

Cross-Site-Request-Forgery-blog-image

With more web security threats emerging daily, modern developers and security professionals can’t afford to overlook the ongoing threat posed by cross-site request forgery (CSRF) attacks. 

CSRF attacks trick users into performing unintended actions that give attackers access to protected systems. Relying on outdated assumptions about how CSRF works can lead to missteps and open the door to serious data breaches.

What is cross-site request forgery?

Many web applications rely on tools such as third-party scripts, AI-enhanced personalization engines, and cross-origin functionality to deliver dynamic content, enhance user experience, and enable integrated services. 

CSRF web attacks target authenticated sessions within a user’s web application browser. They manipulate a browser’s functionality by issuing unauthorized HTTP requests to a server. These web attacks use existing session credentials, such as session IDs, tokens, and cookies. 

Instead of stealing data directly, hackers use CSRF to prompt users to take unwanted actions that unintentionally create software vulnerabilities. As with social engineering, the victim of the attack has no idea what’s happening. Bad actors rely on the same-origin policy, which causes session cookies to be automatically included in web browser HTTP requests.

For example, an attacker might embed an image tag or JavaScript snippet into an email. If the user clicks it, they unknowingly send a request to the target site that includes their session cookies. Because the user is authenticated, the server considers the request legitimate and processes it as a valid POST request without requiring additional validation. 

Why is additional protection needed?

Because CSRF attacks require minimal user interaction, they often go undetected, making them particularly dangerous. Even though a cookie might be marked as Secure or HttpOnly, it still gets automatically attached by a browser. Using them without additional backup security measures is insufficient to protect against CSRF. 

For example, a cyber attacker could use a forged HTTP request to change a user’s email address or modify configuration settings whenever the user logs in. Even seemingly harmless GET requests can trigger sensitive actions if the application doesn’t enforce method restrictions or CSRF checks. 

Developers often assume that setting basic cookie flags or relying on browser policies is sufficient. But modern web applications require more deliberate defense mechanisms, such as:

Without proper server-side validation, any application could be vulnerable to CSRF exploits. To prevent significant damage, systems must be designed with this threat in mind. 

How CSRF attacks work

The best way to understand how dangerous CSRF attacks can be is to examine a common scenario that hackers often use. The following illustrates how CSRF succeeds when inadequate protections are in place around a web application. 

1. User logs in

A user decides to log into their online bank account to check their current balance. They go to the URL https://mybank.com and enter their credentials. After verifying the entered credentials, the bank site creates a new user session, which is tracked by a secure cookie. Here’s how it looks from a code perspective:

Set-Cookie: sessionID=pdqr5678; Secure; HttpOnly; SameSite=None

The cookie is stored and automatically included in subsequent requests to the same URL. People often fail to properly log out after performing an online action. For example, the user leaves the tab open after verifying their checking account balance, meaning their session remains active and open to a CSRF attack. 

2. User visits a malicious site

After leaving the banking site, the user checks their email and sees an email offering a discount on a pair of earbuds they’ve been eying. The user clicks the link in the email, which directs them to the site https://bigdiscounts.com. Unbeknownst to the user, the site is malicious and contains a hidden CSRF payload. 

Below is an example of a hidden HTML form designed to target the user’s banking site:

<body onload="document.forms[0].submit()">

<form action="https://mybank.com/transfer" method="POST">

<input type="hidden" name="to" value="hackerexternalaccount" />

<input type="hidden" name="amount" value="7500" />

</form>

</body>

3. Browser includes the previous session cookie

When the user’s browser tries to load the above form, their previously validated session cookie gets included. That means https://mybank.com believes the action is legitimate because the browser issued the original cookie. The browser cannot distinguish a forged request from a legitimate one. It simply sends the session cookie because the domain matches. This is how all browsers behave unless specifically restricted. 

Many modern browsers allow users to block third-party cookies or apply strict SameSite policies. Without those protections, malicious requests are treated as valid. 

4. Site processes request

Once the user’s banking site receives the request with a valid cookie, it confirms that the user is logged in. If no other verification methods exist, the site looks at the transfer request and attempts to process it, assuming it’s a legitimate, state-changing request. The user is entirely unaware that they’ve just submitted a request to transfer $7,500 from their bank account because of the CSRF.

Applications and functions that are most vulnerable to CSRF

Web applications typically rely on state-changing operations within an authenticated user session, making them vulnerable to CSRF. This also applies to functions designed to update user data, modify system state, or perform other sensitive operations. Rather than exploiting code vulnerabilities, CSRF takes advantage of web applications’ trust in a user’s browser.

Common CSRF targets

HTTP POST, PUT, and DELETE requests are often exploited when they perform operations such as:

  • Changing passwords: Bad actors often focus on endpoints built to allow users to update their credentials.
  • Money transfers: As shown in the example above, CSRF is often used to trick financial applications into moving money into a hacker’s account.
  • Deleting data and user info: File management systems, content management systems (CMS), and administrative portals can be targeted for their ability to remove or purge records.
  • One-click purchases: Exploitation of e-commerce platforms with a one-click purchase mechanism.

Common CSRF protection misconfigurations

Many frameworks, such as ASP.NET Core, offer built-in CSRF protections, but they must be correctly configured. Common mistakes include:

  • Not configuring middleware correctly: A developer might disable CSRF protection when testing or because of issues integrating with a third-party system.
  • Placing tokens in the wrong place: Tokens in URLs are prone to being cached in server logs or browser history, where attackers can retrieve and reuse them.
  • Mismanaging sessions: Allowing tokens to be shared across multiple sessions or failing to invalidate tokens once a user logs out can leave an opening for a CSRF attack.

Risky cookie behaviors that increase CSRF susceptibility

Anti-CSRF mechanisms should always be used to distinguish legitimate from forged requests. Poor cookie configuration increases risk:

  • Lack of a SameSite attribute: SameSite=None permits cross-site requests and can increase vulnerability without other safeguards.
  • Not using Secure or HttpOnly flags: Unmarked cookies can be intercepted (if sent over HTTP) or accessed via JavaScript.
  • Extended sessions: Persistent logins or “remember me” tokens expand the attack window for CSRF exploits.

Impacts of CSRF

The consequences of a successful CSRF attack can be severe, ranging from unauthorized account changes to full-scale data breaches:

  • Financial losses and emergency remediation costs
  • Operational disruption as teams rush to patch systems
  • Regulatory violations, especially in finance and healthcare (e.g., HIPAA, PCI DSS)
  • Loss of customer trust and user attrition
  • Reputational damage

The following are a few recent examples of CSRF incidents and their consequences.

Ruby on Rails vulnerability enables CSRF protection bypass

Recently, a critical flaw in the Ruby on Rails framework was discovered where its CSRF protection could be bypassed, exposing applications to unauthorized state-changing requests. As a result, attackers could perform actions for authenticated users, such as changing account settings or executing transactions, compromising user data, and application integrity.

Zimbra GraphQL CSRF flaw exposes 200,000+ organizations

A CSRF vulnerability (CVE‑2025‑32354) in Zimbra Collaboration Suite’s GraphQL endpoint allowed attackers to execute unauthorized operations like modifying contacts, changing account settings, and exfiltrating emails without user interaction. With over 200,000 organizations at risk, this flaw enabled full account takeover and data theft until it was patched in Zimbra 10.1.4.

Jenkins CSRF vulnerability permits unauthorized UI manipulation

In March 2025, a CSRF vulnerability (CVE‑2025‑27624) in Jenkins allowed malicious actors to toggle side panel widget states via GET requests and inject arbitrary identifiers into user profiles. These types of incidents could pave the way for persistent UI manipulation or stored XSS attacks. Jenkins fixed the issue in versions 2.500 and 2.492.2 by requiring POST requests and enforcing CSRF validation.

How to combat CSRF attacks

Below are some effective security best practices that developers and security teams can use to protect applications.

1. Use CSRF tokens

CSRF tokens are unpredictable, unique values typically generated per session or request and tied to a user’s authenticated state. They’re included with every state-changing request and validated server-side. If the token doesn’t match what’s expected, the request is rejected, thus blocking unauthorized actions triggered by forged requests.

2. Enforce SameSite cookies

The SameSite cookie attribute restricts whether cookies are sent with cross-origin requests. It offers three modes:

  • Strict: Only sends cookies with requests originating from the same domain.
  • Lax: Allows cookies for same-site requests and top-level navigations (e.g., link clicks). This is the default in most modern browsers.
  • None: Allows cookies with any request, including third-party. This must be paired with the Secure flag and should be used only when necessary (e.g., third-party integrations).

3. Require user interaction for critical actions

Reinforce sensitive workflows by requiring users to explicitly confirm their actions. This can include double password entry, one-time passcodes (OTPs), CAPTCHAs, or confirmation dialogs. In essence, the goal is to add friction that automated CSRF exploits can’t bypass.

4. Use HTTP headers and referer validation

Check Origin and Referer headers on incoming HTTP requests to confirm they come from trusted sources. For example, a request to https://mybank.com/transfer should have a matching origin header from https://mybank.com. Note that some privacy settings and browser extensions can strip or block these headers, so this technique should be used as part of a layered security strategy, not as a standalone defense.

CSRF versus XSS: Similarities and differences

While CSRF and cross-site scripting (XSS) are both serious security threats, they operate in fundamentally different ways.

XSS allows attackers to inject malicious executable code (typically JavaScript) into a webpage viewed by another user. This can be used to hijack sessions, log keystrokes, or redirect users to malicious sites.

By contrast, CSRF manipulates a user’s browser into sending unauthorized requests without their knowledge. While XSS exploits the user’s trust in a website, CSRF exploits the website’s trust in the user’s browser. Importantly, CSRF attackers cannot see responses or interact directly with applications, but they can still force state-changing actions, like changing a password or submitting a form.

Both attack types undermine core pillars of trust in web applications. CSRF can result in unauthorized transactions or account changes, while XSS may lead to data theft, malware injection, or session compromise.

AspectCSRFXSS
Attack MethodTricks the browser into sending unauthorized requestsInjects malicious code (usually JavaScript) into a webpage
Trust ExploitedWebsite’s trust in the user/browserUsers’ trust in the website
Attacker CapabilitiesCannot see responses or interact directlyCan read data, steal cookies, hijack sessions, etc.
Common ConsequencesUnauthorized transactions, changed settingsData theft, session hijacking, and malware injection
User InteractionRequires the user to be authenticated and perform an actionCan be triggered just by visiting a malicious or compromised page

How tools and frameworks defend against CSRF

Let’s look at CSRF protections offered by popular development frameworks. These built-in protections make it easier to enforce CSRF defenses without starting from scratch.

  • Spring Security: Embeds synchronizer tokens in web forms that must be validated with every request that modifies the server state. 
  • ASP.NET Core: Provides anti-forgery tokens within the MVC stack. Adding a ValidateAntiForgeryToken attribute to controller actions forces POST, PUT, and DELETE requests to carry a valid token. 
  • Django: Uses middleware and form rendering helpers to enable default CSRF protection. Adding a {%csrf_token%} tag automatically embeds a token in a form. The framework then performs validations upon each form submission. 
  • Laravel: Uses middleware that checks for a valid token on every state-changing request.
  • Ruby on Rails: This framework embeds authenticity tokens in forms and meta tags to protect against CSRF. Adding a protect_from_forgery directive to controllers enforces request validation. 

Protect user trust by preventing CSRF

Built-in protections in frameworks are a strong start, but they’re not a complete defense. CSRF attacks exploit trusted sessions at the browser level, and attackers often combine them with reverse engineering or code tampering to find deeper weaknesses in your application.

At the foundation, make sure your defenses include adding CSRF tokens, validating request headers, configuring SameSite cookies, and prompting user actions. These are essential for verifying request authenticity and minimizing the risk of unauthorized actions within trusted sessions.

You can also strengthen your defense even further and harden your application from the inside out with PreEmptive. PreEmptive’s app protection tools add layers of security that complement server-side defenses, including:

Together, these protections help reduce the risk of exploits like CSRF and strengthen your app’s overall security posture. Request your free trial of PreEmptive today and see how layered defenses can protect your applications from even the most deceptive threats.

In This Article:

Start a Free Trial of PreEmptive Today