Application Security

Cross-Site Request Forgery: Attacks, Protection & Examples

By Rajesh N

12 min read

Cross-Site Request Forgery: Attacks, Protection & Examples

Web applications are increasingly targeted by sophisticated attacks, and Cross-Site Request Forgery (CSRF) remains a common security risk. CSRF exploits the trust between authenticated users and web applications by tricking a user’s browser into performing actions without their knowledge, such as changing account settings, transferring funds, or posting content without permission.

Developers, security teams, and organizations need to understand CSRF to protect sensitive data, secure user sessions, and prevent unauthorized actions. Effective CSRF mitigation combines proper session management, CSRF tokens, secure cookie settings, and regular security testing to reduce the risk of unauthorized requests.

Importance of CSRF Detection and Prevention

Detecting and preventing CSRF attacks is essential for modern web applications. These attacks exploit authenticated sessions, allowing attackers to perform harmful actions users have valid credentials. SQL injection or XSS, CSRF can operate silently by abusing the trust between a user’s browser and the server, making these attacks harder to detect.

Controls such as anti-CSRF tokens, SameSite cookie attributes, and secure handling of state-changing endpoints help prevent attackers from exploiting these weaknesses. Effective CSRF prevention ensures that sensitive requests, such as form submissions or API calls, originate from trusted sources, helping protect user accounts and maintain application integrity.

Why Understanding CSRF is Critical

  • Developers: Integrate security into the development lifecycle by understanding CSRF and implementing protections such as synchronizer tokens, double-submit cookies, and SameSite cookie enforcement to ensure state-changing requests are legitimate.
  • Security Teams: Include CSRF in security testing frameworks, conduct regular assessments, and ensure penetration tests cover relevant CSRF attack scenarios.
  • Enterprises: Failing to address CSRF can result in unauthorized transactions, regulatory penalties, reputational damage, and loss of customer trust.

What is Cross-Site Request Forgery (CSRF)?

Cross-Site Request Forgery (CSRF) is a web application attack that tricks a user’s browser into performing unauthorized actions on a trusted site where the user is already authenticated. In a CSRF attack, the attacker takes advantage of browsers automatically sending credentials such as session cookies, tokens, or HTTP headers with requests to a specific site. Visiting a malicious page, clicking a crafted link, or loading a hidden image can cause the browser to send a request that appears legitimate to the target application without the user’s knowledge.

How CSRF Exploits Authenticated Sessions

CSRF attacks take advantage of authenticated sessions by abusing the trust between a user and a web application. When a user logs into a site such as a banking portal or online store, the browser stores session cookies and automatically sends them with subsequent requests. A malicious site can take advantage of this behavior by sending crafted requests to the trusted application through the user’s browser.

If a user is logged into a banking dashboard, a hidden request from another site could attempt to initiate a fund transfer. If the application does not have proper CSRF protections, the server could process the request as if it came from the authenticated user.

Real-World Impact on Web Applications

The real‑world impact of CSRF can be significant:

CSRF Real-World Impact on Web Applications

Difference Between CSRF and Other Web Vulnerabilities

CSRF is often discussed alongside other web vulnerabilities like Cross-Site Scripting (XSS) or SQL Injection, but it differs in how attackers abuse authenticated requests.

  • CSRF vs XSS: XSS allows attackers to inject malicious scripts into trusted web pages, typically enabling them to steal user data or manipulate page content. CSRF, on the other hand, forces the user’s browser to submit requests without injecting code into the target application.
  • CSRF vs SQL Injection: SQL Injection targets the database layer by manipulating query syntax, whereas CSRF abuses how web applications process authenticated requests.
  • CSRF vs Session Hijacking: Session hijacking steals or guesses session tokens to impersonate a user. CSRF doesn’t steal credentials; it exploits a user’s existing authenticated state to perform actions. 

How CSRF Attacks Work

Cross-Site Request Forgery (CSRF) attacks exploit the trust a web application places in a user’s browser. Understanding how these attacks work helps developers and security teams implement effective prevention measures.

Step-by-Step Attack Flow

How Cross-Site Request Forgery  Attacks Work

Examples Illustrating CSRF in Action

  • Online Banking: A user logged into an online bank unknowingly triggers a hidden request on a malicious site that initiates a transfer to the attacker’s account.
  • E-Commerce Platforms: CSRF can change shipping addresses or place orders without the user’s consent.
  • Social Media Sites: A CSRF attack can post messages, modify account settings, or follow/unfollow users without authorization.

Importance of Understanding Session Management and Cookies

CSRF attacks rely heavily on how browsers handle session cookies and authentication tokens. Properly managing sessions and using secure cookie attributes such as:

  • HttpOnly: prevents JavaScript access to cookies
  • Secure: ensures cookies are sent only over HTTPS
  • SameSite: restricts cookies from being sent in cross-site requests

Common CSRF Attack Scenarios

Cross-Site Request Forgery (CSRF) attacks exploit the trust between a user’s browser and a web application, allowing attackers to perform unauthorized actions without the user’s knowledge. Understanding common CSRF attack scenarios helps developers and security teams apply appropriate protections to safeguard users and systems.

Unauthorized Fund Transfers on Banking Portals

This is the classic CSRF scenario. Banking applications often use predictable URLs to initiate transfers.

  • The Scenario: A victim is logged into their bank account. The session is active, they visit a malicious site.
  • The Execution: The malicious site contains a hidden request often triggered via a simple link or script, that calls the bank’s transfer API.
  • The Impact: Since the browser automatically attaches the user’s session cookie, the bank processes the transaction as if the user initiated it via the banking dashboard.

Changing Account Settings Without Consent

Attackers often use CSRF to weaken security or gain persistent access to an account by altering its configuration.

  • The Scenario: An attacker targets a profile management page where users can update their email or password.
  • The Execution: The attacker crafts a request that updates the account’s registered email to one they control.
  • The Impact: Once the email is changed, the attacker can trigger a password reset on the platform. The reset link is sent to the attacker’s email, effectively granting them full, permanent control over the victim’s account.

Social Media Account Hijacking

Social media platforms are prime targets for CSRF because they rely heavily on actions like following, liking, or posting, which often do not require complex authentication for every single click.

  • The Scenario: A victim is browsing a social network and clicks a malicious advertisement or link.
  • The Execution: The link triggers a background request to the social platform to Post this link or follow this user.
  • The Impact: The victim’s account is used to spread spam or malicious content to their entire friend list. Because the post comes from a trusted friend, other users are much more likely to click it, turning the account into a tool for automated malware distribution.

Cross-Site Request Forgery Protection Techniques

Protecting a web application from Cross-Site Request Forgery (CSRF) requires multiple security controls. CSRF takes advantage of browsers automatically sending cookies with requests, so server-side checks are needed to verify that state-changing requests are intentional and authorized.

The following are some of the commonly used techniques for preventing CSRF attacks.

Anti-CSRF Tokens (Synchronizer Token Pattern)

The Anti-CSRF token is the gold standard for CSRF prevention. The server generates a unique, cryptographically strong, and unpredictable token for the user’s session.

  • How it works: The server includes this token as a hidden input field. When the user submits the form, the server verifies that the submitted token matches the one stored in the user’s session.
  • Why it works: An attacker on a different domain cannot read or guess this unique token, so any forged request they attempt to submit will lack the valid token, causing the server to reject it.

SameSite Cookie Attributes

The SameSite attribute is a browser-level security feature that tells the browser whether to send cookies with cross-site requests.

  • Strict: The cookie is never sent if the request originates from a different site. This is the most secure option but can impact user experience.
  • Lax: The cookie is not sent on cross-site subrequests but is sent when a user follows a standard link to the origin site.

Double-Submit Cookies

The Double-Submit pattern is a stateless CSRF defense that is useful for applications that cannot easily maintain session state on the server.

  • How it works: When a user visits the site, the server sends a random value in a cookie. When the user submits a form, the client is required to send the same value in a hidden form field or a custom HTTP header.
  • Why it works: An attacker can trigger a request, but they cannot read or modify the cookie due to the browser’s Same-Origin Policy (SOP). They cannot force a request where the form value and the cookie value match.

Origin and Referrer Header Validation

Modern web servers can inspect the Origin and Referrer HTTP headers to determine the source of a request.

  • How it works: The server checks these headers to verify that the request originated from a trusted domain. If the header is missing or indicates an untrusted source, the request is denied.
  • Important Note: This should be a defense-in-depth measure. These headers can sometimes be stripped by privacy-focused proxies or browser extensions, and they are not a substitute for CSRF tokens.

CSRF Detection and Prevention Tools

Detecting and preventing Cross-Site Request Forgery (CSRF) requires a combination of secure coding practices and security testing. CSRF vulnerabilities can be hidden in application workflows and business logic, so manual code review alone may not identify every issue.

The following tools and strategies can help identify and mitigate CSRF vulnerabilities throughout the development lifecycle.

Automated Security Scanners

Automated vulnerability scanners are essential for identifying CSRF weaknesses across web applications:

  • Scan forms, APIs, and state-changing endpoints for missing anti-CSRF tokens.
  • Detects misconfigurations, insecure cookies, and session handling flaws.
  • Generate reports highlighting high-risk CSRF vulnerabilities for remediation.

Web Application Firewalls (WAFs)

A Web Application Firewall (WAF) can provide an additional security layer by inspecting and filtering HTTP and HTTPS traffic before requests reach the application.

  • Filtering requests for suspicious or malformed input.
  • Enforcing cookie and session validation rules.
  • Blocking known attack signatures and suspicious request patterns.

Security Testing Platforms (Burp Suite, OWASP ZAP)

Security teams can also incorporate CSRF checks into broader API security testing when applications rely on APIs for state-changing operations.

  • Burp Suite: Offers CSRF token analysis, automated scanning, and manual testing workflows.
  • OWASP ZAP: Open-source tool for discovering CSRF vulnerabilities and simulating attack scenarios.

Real-World Cross-Site Request Forgery Examples

Cross-Site Request Forgery (CSRF) is often called a one-click attack or session riding because it forces an authenticated user to unknowingly execute unwanted actions on a web application. Because the application trusts the user’s browser, it processes these forged requests as legitimate commands.

Banking Transaction Hijack Scenario

CSRF can allow attackers to transfer funds without user consent.

  • A user logs into their bank account and is authenticated with a session cookie.
  • The attacker embeds a malicious request in a website or email.
  • When the victim visits the malicious page, the browser automatically sends the session cookie with the crafted request.
  • The bank executes the transaction as if the user initiated it, resulting in unauthorized fund transfers.

Lessons Learned and Remediation Approaches

Real-world CSRF incidents provide critical insights for prevention:

CSRF Remediation Approaches

Best Practices for Preventing CSRF

Cross-Site Request Forgery (CSRF) attacks exploit authenticated user sessions to perform unauthorized actions. Implementing strong request validation and secure session controls helps protect web applications from CSRF attacks.

The following strategies can help prevent CSRF attacks:

1. Protect State-Changing Requests

  • Apply CSRF protection to requests that create, modify, or delete data.
  • Avoid using GET requests for state-changing operations.
  • Apply additional validation to sensitive actions such as payments and account changes.

2. Secure Session Cookies

  • Use the Secure attribute to transmit cookies only over HTTPS.
  • Use HttpOnly to prevent client-side scripts from accessing session cookies.
  • Configure appropriate session expiration and renewal controls.

3. Restrict Cross-Origin Requests

  • Configure CORS policies to allow only trusted origins.
  • Avoid permissive cross-origin settings for authenticated endpoints.
  • Review cross-origin access for sensitive APIs and application functions.

4. Add Protection for Sensitive Actions

  • Require re-authentication for high-risk operations.
  • Use multi-factor authentication for sensitive account or privilege changes.
  • Apply additional verification to financial and administrative actions.

Challenges and Limitations

Cross-Site Request Forgery (CSRF) protection techniques like tokens, SameSite cookies, and header validation are effective, modern web environments introduce challenges that can make mitigation complex. Understanding these limitations is essential for developers, security teams, and enterprises to design robust protections without compromising usability.

Complex Modern Web Applications and SPA Frameworks

Single Page Applications (SPAs) and modern JavaScript frameworks often rely heavily on asynchronous API requests and dynamic content loading. CSRF protection in these environments can be challenging because:

  • Traditional token placement in forms may not cover all AJAX or API calls.
  • Dynamic routing and session handling can make token verification difficult.

Third-Party Integrations and Cross-Domain Requests

Many web applications depend on external APIs, payment gateways, and third-party widgets. CSRF protection can be complicated in these scenarios because:

  • Cross-domain requests may not support token validation by default.
  • Third-party content can inadvertently bypass SameSite cookie restrictions.

Misconfigured Security Headers and Cookie Policies

Even with proper CSRF mechanisms, incorrectly configured cookies or security headers can undermine protection:

  • Missing or improperly set SameSite, Secure, or HttpOnly flags can leave session cookies exposed.
  • Referrer and Origin header validation may fail if proxies, load balancers, or CDN caching alter headers.

Conclusion

Cross-Site Request Forgery (CSRF) remains a serious web application threat, exploiting authenticated user sessions to perform unauthorized actions. Implementing anti-CSRF tokens, SameSite cookies, origin/referrer validation, and secure session management, alongside developer training and automated testing, is essential to protect data, maintain session integrity, and reduce risk.

SecureLayer7 provides advanced CSRF detection and prevention solutions to safeguard your applications and ensure resilient, secure digital services.

Partner with SecureLayer7 to implement best-in-class protections and stay ahead of evolving cyber threats.

Frequently Asked Questions (FAQs)

What is Cross-Site Request Forgery (CSRF)?

CSRF is a web vulnerability where attackers trick a user’s browser into performing unauthorized actions on a trusted web application by exploiting the user’s active session. Examples include unauthorized fund transfers, account changes, or content postings.

How does a CSRF attack work?

A CSRF attack typically occurs when a victim logs into a web application and maintains an active session. The attacker creates a malicious request targeting a state-changing operation, and the victim unknowingly triggers it.

How can web applications implement CSRF protection?

Web applications can use anti-CSRF tokens, SameSite cookies, double-submit cookies, and Origin or Referrer header checks to validate requests. Sensitive actions can also require additional verification, such as re-authentication, CAPTCHA, or two-factor authentication.

What are real-world examples of CSRF attacks?

CSRF attacks can affect banking portals through unauthorized fund transfers, web portals through account setting changes, social media platforms through unauthorized posts or follows, and e-commerce applications through unwanted cart or checkout changes.

How is CSRF different from XSS?

CSRF exploits the trust a website has in an authenticated user’s session and does not require script injection. XSS exploits the trust a user has in a website by injecting malicious scripts that execute in the user’s browser.