Ctrl + K
Security8 min read

CSRF Explained

Understand CSRF attacks, why they occur, how browsers handle cookies and the techniques used to prevent Cross-Site Request Forgery.

Published: 2026-08-07

Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks a user's browser into sending an unwanted request to a website where the user is already authenticated. Because browsers automatically include cookies with many requests, a forged request may be processed as if it were intentionally made by the legitimate user.

CSRF attacks target state-changing actions such as changing passwords, updating account settings, transferring money or deleting data. The attacker does not need to know the user's password—only that the user is currently logged into the vulnerable website.

What Is CSRF?

CSRF occurs when a malicious website, email or message causes a victim's browser to send an authenticated request to another website without the user's knowledge or consent. Since the browser automatically attaches authentication cookies, the target server may accept the forged request as legitimate.

Why CSRF Happens

Browsers are designed to automatically include cookies with requests to the appropriate domain. While this behavior enables convenient user sessions, it also creates an opportunity for attackers if applications do not verify that requests genuinely originate from their own pages.

Example Attack Scenario

  • The user logs into their online banking website.
  • The browser stores the authentication cookie.
  • The user visits a malicious website in another tab.
  • The malicious page silently submits a request to the bank.
  • The browser automatically includes the banking cookie.
  • If CSRF protection is missing, the server processes the request.

Simplified Attack Flow

User Logs In
↓
Session Cookie Stored
↓
User Visits Malicious Website
↓
Forged Request Sent
↓
Cookie Included Automatically
↓
Server Executes Request

Common Targets

Any operation that changes server-side data can potentially become a CSRF target if proper protections are missing.

ActionPossible Risk
Password changeAccount takeover
Email updateLoss of account access
Money transferFinancial loss
Delete accountPermanent data loss
Change permissionsPrivilege escalation

CSRF vs XSS

CSRF and Cross-Site Scripting (XSS) are different vulnerabilities. CSRF abuses the browser's automatic authentication behavior, while XSS injects malicious scripts into trusted web pages. Although different, XSS can sometimes bypass certain CSRF defenses if attackers can execute JavaScript on the vulnerable site.

VulnerabilityPrimary Goal
CSRFForge authenticated requests
XSSExecute malicious JavaScript

Can APIs Be Affected?

Traditional cookie-based web applications are the primary targets for CSRF. APIs that use bearer tokens stored outside automatically sent cookies are generally less vulnerable, although implementation details still matter.

💡 If your application relies on cookies for authentication, always implement CSRF protection for requests that modify server-side data.
⚠️ Using HTTPS alone does not prevent CSRF attacks. HTTPS encrypts network traffic but does not verify whether a request was intentionally initiated by the user.

How CSRF Protection Works

CSRF defenses ensure that requests modifying server-side data originate from the legitimate application rather than from an external website. Modern applications often combine multiple protection mechanisms to provide stronger security against forged requests.

CSRF Tokens

The most common defense is the CSRF token. The server generates a unique, unpredictable value and embeds it into forms or responses. When the browser submits a request, the application sends the token back to the server, which verifies that it matches the expected value before processing the request.

Browser Requests Form
↓
Server Generates CSRF Token
↓
User Submits Form
↓
Token Verified
↓
Request Accepted

SameSite Cookies

Modern browsers support the SameSite cookie attribute, which limits when cookies are automatically included in cross-site requests. Properly configured SameSite cookies significantly reduce the risk of successful CSRF attacks.

SameSite ValueBehavior
StrictCookies sent only for same-site requests
LaxAllows some top-level navigation requests
NoneCookies sent for cross-site requests (requires Secure)

Origin and Referer Validation

Servers can examine the Origin or Referer HTTP headers to determine where a request originated. If the request comes from an unexpected domain, the server can reject it before performing any sensitive operation.

Double Submit Cookie Pattern

Another common technique stores a CSRF token in a cookie and sends the same value in a request header or form field. The server compares both values, rejecting the request if they do not match.

State-Changing Requests

CSRF protection is primarily required for operations that modify data, such as POST, PUT, PATCH and DELETE requests. Read-only GET requests should generally not perform actions that change application state.

HTTP MethodTypical CSRF Risk
GETLow (should be read-only)
POSTHigh
PUTHigh
PATCHHigh
DELETEHigh

CSRF and CORS

Cross-Origin Resource Sharing (CORS) and CSRF solve different security problems. CORS controls which websites may access resources across origins, while CSRF protection verifies that authenticated requests were intentionally initiated by the user. Enabling CORS alone does not eliminate CSRF risks.

Modern Framework Support

Many web frameworks automatically generate and validate CSRF tokens for server-rendered forms. Even with built-in protection, developers should understand how these mechanisms work and ensure they remain enabled for sensitive endpoints.

  • Use CSRF tokens for state-changing requests.
  • Enable SameSite cookies where appropriate.
  • Validate Origin or Referer headers when possible.
  • Keep GET requests free of side effects.
  • Use HTTPS together with CSRF protections.
💡 Combining CSRF tokens with SameSite cookies provides stronger protection than relying on either mechanism alone.
⚠️ Disabling CSRF protection for convenience can expose authenticated users to unauthorized account actions, even if they never interact directly with an attacker.

Common Mistakes

CSRF protection is often misunderstood because attacks rely on normal browser behavior rather than software vulnerabilities in the browser itself. Many applications become vulnerable due to incorrect assumptions about cookies, HTTP methods or cross-origin requests.

  • Assuming HTTPS prevents CSRF attacks.
  • Using GET requests for operations that modify server-side data.
  • Disabling built-in CSRF protection in web frameworks.
  • Relying only on CORS for request validation.
  • Ignoring SameSite cookie settings.
  • Failing to validate CSRF tokens on every state-changing request.

Best Practices

  • Generate unpredictable CSRF tokens for authenticated sessions.
  • Validate CSRF tokens on every state-changing request.
  • Use SameSite cookies whenever possible.
  • Restrict sensitive operations to POST, PUT, PATCH and DELETE requests.
  • Validate Origin or Referer headers when appropriate.
  • Combine CSRF protection with strong session management and HTTPS.
💡 Even if your framework provides automatic CSRF protection, verify that it remains enabled after upgrades, configuration changes or the introduction of custom API endpoints.
⚠️ CSRF protection should never be disabled simply because an application is behind authentication. Authenticated sessions are exactly what CSRF attacks attempt to abuse.

Frequently Asked Questions

Does HTTPS prevent CSRF attacks?

No. HTTPS encrypts data transmitted between the browser and the server, but it does not verify whether a request was intentionally initiated by the user. CSRF protection mechanisms are still required.

Are APIs vulnerable to CSRF?

Cookie-based APIs can be vulnerable because browsers automatically send cookies with requests. APIs that use bearer tokens stored outside cookies are generally less susceptible, but the overall implementation still matters.

What is the purpose of a CSRF token?

A CSRF token is a unique, unpredictable value generated by the server. It proves that a state-changing request originated from the legitimate application rather than from a malicious third-party website.

Does SameSite completely replace CSRF tokens?

No. SameSite cookies significantly reduce CSRF risk, but many applications combine SameSite with CSRF tokens and Origin validation for stronger protection.

Can XSS bypass CSRF protection?

In some cases, yes. If attackers can execute JavaScript within the trusted website through an XSS vulnerability, they may be able to obtain CSRF tokens or perform authenticated actions directly. Preventing XSS remains an essential part of web application security.

Helpful Security Tools

A Cookie Parser helps inspect cookies returned by web applications, a Cookie Generator creates properly formatted Cookie headers for testing, a Set-Cookie Generator builds valid Set-Cookie response headers with attributes such as SameSite and Secure, an HTTP Header Viewer displays request and response headers for debugging, and a CORS Header Generator assists in creating Access-Control-* headers for cross-origin resource sharing configurations.

Conclusion

Cross-Site Request Forgery exploits the browser's automatic handling of authenticated requests rather than weaknesses in encryption or authentication itself. By combining CSRF tokens, SameSite cookies, Origin validation and secure application design, developers can effectively protect users from unauthorized actions performed on their behalf. Understanding how CSRF works is an essential part of building secure modern web applications.