Fact-checked by Grok 2 weeks ago

Cross-site request forgery

Cross-site request forgery (CSRF), also known as XSRF or session riding, is a type of that allows an attacker to induce a victim to perform unintended state-changing actions on a where the victim is . In such attacks, the malicious actor exploits the 's automatic inclusion of authentication credentials, like session , in cross-origin requests, tricking the victim's into sending forged requests to the target site without their awareness or consent. The mechanics of a CSRF attack typically involve embedding malicious code, such as an image tag or , on a site controlled by the attacker or in an , which prompts the to issue an HTTP request to the vulnerable application. For example, if a user is logged into their and visits a malicious webpage, that page could silently submit a request using the bank's legitimate , leveraging the active session to execute the transaction as if initiated by the user. This vulnerability relies on the absence of mechanisms to distinguish legitimate user-initiated requests from forged ones, making it effective against applications that use for session without additional protections. CSRF poses significant risks, including unauthorized financial transactions, account modifications, or data deletions, as it bypasses normal access controls by impersonating legitimate user actions. It has been a persistent threat since the early , with real-world exploits such as the 2008 uTorrent incident that distributed via forged requests on a large scale. Although not listed as a standalone category in the Top 10 2025 (release candidate), CSRF remains a critical component of broader issues like broken and is addressed in standards like CWE-352 for its high potential impact on authenticated users. Effective prevention strategies focus on ensuring request authenticity through methods like the synchronizer token pattern, where a unique, unpredictable token is generated per session and included in legitimate forms or requests, then validated server-side to block forged submissions. Additional defenses include validating the ** or headers to confirm requests originate from trusted domains, requiring re-authentication or for sensitive actions, and setting the SameSite attribute on cookies (e.g., SameSite=Strict or Lax) to restrict their inclusion in cross-site requests. Modern frameworks often provide built-in CSRF protections, such as Django's csrf_token template tag or CSRFGuard, emphasizing defense-in-depth to mitigate this longstanding web threat.

Fundamentals

Definition

Cross-Site Request Forgery (CSRF), also abbreviated as XSRF and sometimes referred to as a one-click attack or session riding, is a type of malicious web exploit in which an attacker tricks an authenticated user into executing unwanted actions on a target without the user's knowledge or consent. The attack leverages the user's existing credentials, typically stored in session , to perform state-changing operations such as transferring funds or modifying settings. CSRF attacks succeed because web browsers automatically attach authentication credentials, like , to HTTP requests sent to the target domain, even when those requests originate from a different (cross-origin) site controlled by the attacker. This behavior enables the exploit with minimal user interaction—often just loading a malicious webpage via a link in an , advertisement, or social engineering ploy—allowing the forged request to appear legitimate to the . In contrast to cross-site scripting (XSS), which injects and executes malicious scripts directly within the vulnerable site to steal data or hijack sessions, CSRF exploits the trust in the user's authenticated session without injecting any code into the target application, relying instead on the inherent transmission of valid credentials.

Characteristics

Cross-site request forgery (CSRF) relies on ambient authority, where web browsers automatically include authentication credentials, such as session cookies, in HTTP requests to a target domain without requiring explicit user confirmation or action from the victim. This implicit transmission of credentials allows attackers to leverage the victim's existing authenticated session to perform unauthorized operations on the target site. The cross-site nature of CSRF distinguishes it from same-origin attacks, as the malicious request originates from a domain different from the vulnerable application's domain, exploiting limitations in the browser's that primarily restricts script access but permits the sending of cross-origin requests via forms, images, or scripts. Specifically, this policy does not block the browser from attaching authentication tokens to non-GET requests sent to the target site, enabling the forgery while preventing direct manipulation of the response. CSRF attacks primarily target state-changing operations that are non-idempotent, such as modifying user profiles, initiating financial transfers, or updating account settings, rather than read-only queries like viewing data, because these actions alter the server's state without the user's intentional input. Such operations are vulnerable precisely because they rely on the context provided by the browser, making them susceptible to forgery when the user interacts with a malicious external site. Browser behavior plays a critical role in CSRF, as HTTP requests—whether via GET, , or other methods—implicitly carry authentication details like cookies when directed to the associated domain, regardless of the request's origin. For instance, while GET requests are often restricted by web applications to safe operations due to their idempotent nature and potential for prefetching, requests (and similar methods) can trigger state changes and include the necessary credentials automatically, heightening their exploitability in cross-site scenarios. This automatic credential inclusion contrasts with explicit flows, where users must re-enter credentials, thereby underscoring the attack's dependence on persistent session mechanisms. For a CSRF attack to succeed, several prerequisites must be met: the victim must be authenticated with an active session on the target website, the must support the transmission of or other ambient credentials, and the victim must interact with the attacker's malicious content, such as loading a forged page or clicking a link that triggers the request. Without an established session, the request would lack the necessary authority to effect changes, rendering the attack ineffective.

Historical Background

Origins and Early Discoveries

The concept of cross-site request forgery (CSRF), initially unrecognized as a distinct threat, emerged in the late and early amid growing awareness of web session vulnerabilities. The first public documentation of the attack type appeared in 2000 on the Bugtraq mailing list, describing a flaw in the ZOPE where authenticated users could be tricked into executing unauthorized actions via cross-site requests that leveraged persistent session . This early report framed the issue as an exploitation of behavior and cookie persistence, without yet assigning a specific name to the technique. In June 2001, security researcher Peter Watkins formally coined the term "Cross-Site Request Forgery" in a Bugtraq mailing list posting, building on prior discussions and linking the attack to the broader "confused deputy" problem originally described by Norm Hardy in 1988. Watkins highlighted how malicious sites could force a user's browser to submit forged requests to trusted applications, exploiting automatic credential transmission without user interaction. This marked the initial public recognition of CSRF as a named vulnerability, though it remained tied to related concepts like session fixation, where attackers manipulated session identifiers to hijack authenticated states. During 2001 and 2002, security forums such as Bugtraq featured additional mentions of the attack, often connecting it to weaknesses in the header, which browsers could suppress or attackers could spoof, enabling forged requests to evade simple origin validation. Prior to the formalization of organizations like in 2001, the threat was predominantly viewed as a byproduct of flawed cookie-handling mechanisms in web applications, rather than an independent requiring specific mitigations. Microsoft security documentation from the era similarly categorized it under confused deputy variants, emphasizing session riding without isolating CSRF as a standalone concern.

Evolution and Recognition

The recognition of cross-site request forgery (CSRF) as a distinct web threat gained momentum in the mid-2000s, transitioning from ad-hoc discussions to formal terminology and industry-wide awareness. The Open Web Application Project () contributed to broader awareness of CSRF in the mid-2000s, including it in the inaugural Top 10 list in 2007 as category A5, ranking it fifth among critical web application risks due to its prevalence in session-based systems lacking request validation. A landmark publication that contributed to early awareness was Matt Mullenweg's 2005 blog post, which explored CSRF vulnerabilities in the context of emerging technologies and their implications for state-changing operations in web applications. A notable early exploitation was the Samy worm on in 2005, which used CSRF combined with XSS to spread rapidly, highlighting the vulnerability's real-world impact. Microsoft's guidance in 2006 further amplified recognition, recommending server-side mitigations like custom headers and token validation in applications to counter forged requests exploiting cookie-based authentication. The threat's influence extended to web standards and browser implementations, prompting refinements in HTTP specifications to reinforce the distinction between safe (e.g., GET) and unsafe (e.g., ) methods for state-changing actions, as outlined in RFC 7231. Browser vendors responded by enhancing cross-origin request handling, laying groundwork for later features like SameSite cookies. Concurrently, CVE reports surged in the late , peaking around 2006-2009 as awareness grew, with CSRF classified under CWE-352 and accounting for a notable portion of web vulnerabilities documented in the . Despite widespread adoption of defenses, CSRF vulnerabilities persist into 2025, particularly in plugins and APIs where token enforcement is inconsistent. For instance, the Ultimate Member plugin suffered a CSRF flaw in versions up to 2.6.0 (CVE-2023-31216), allowing unauthorized form duplication that could lead to further user actions. Similarly, Obsidian's exposed CSRF risks enabling admin password changes and server configuration alterations (e.g., CVE-2022-45130), underscoring ongoing challenges in third-party integrations. These incidents reflect a steady stream of CVEs, with Patchstack reporting over 100 WordPress-related CSRF disclosures in 2023-2025 alone.

Attack Examples

Basic CSRF Scenario

In a basic cross-site request forgery (CSRF) scenario, consider a victim user who is authenticated and logged into an website, such as bank.com, where their session is maintained via . An attacker hosts a malicious webpage on a separate , for example, evil.com, which contains an automatically submitting designed to exploit the victim's active session. This setup relies on the browser's ambient authority, where the victim's credentials are automatically included in requests to the bank without their explicit consent. The attack unfolds in steps: first, the attacker tricks the victim into visiting the malicious page, perhaps via a phishing email or a link on a compromised site. Upon loading, the page uses JavaScript to submit a form that sends a POST request to the banking site's transfer endpoint, such as https://bank.com/transferFunds. The request includes hidden fields with parameters for the fraudulent action, like transferring a large sum to the attacker's account, and the browser attaches the victim's authentication cookies to the request as if it were a legitimate action initiated by the user. A simple example of the malicious HTML form might appear as follows:
html
<form action="https://bank.com/transferFunds" method="post" id="maliciousForm">
    <input type="hidden" name="amount" value="1000000" />
    <input type="hidden" name="account" value="attacker_account" />
</form>
<script>
    document.getElementById("maliciousForm").submit();
</script>
This code causes the browser to immediately POST the data to the target site upon page load. As a result, the unauthorized fund transfer completes successfully on the banking site, appearing as a legitimate from the , all while the remains on the attacker's without any visible indication of the action.

Forging Login and State-Changing Requests

In login CSRF attacks, an attacker exploits the authentication mechanism of a target website by forging a login request using their own credentials through the 's . This occurs when the , who may be unauthenticated or logged into their own account, visits a malicious webpage controlled by the attacker. The malicious page typically uses a hidden HTML form or to automatically submit the target's with the attacker's username and , causing the 's to establish an authenticated session for the attacker's account. Once the forged login succeeds, the malicious site can issue state-changing requests to the target website using the active session now present in the victim's , which authenticates as the attacker's . These requests can perform actions on the attacker's , such as escalating privileges or initiating transfers, potentially bypassing site restrictions like IP-based checks by leveraging the victim's connection. However, the primary risks arise when the victim, unaware of the session change, interacts with the site and adds —such as information or other sensitive details—to the attacker's , allowing the attacker to access it later. This can also expose the victim's browsing activity or identifiers (e.g., ) linked to the attacker's , leading to privacy violations or further exploitation. Such attacks are especially potent against websites with persistent sessions or those lacking clear indicators of the logged-in during .

Technical Considerations

HTTP Verbs in CSRF

Cross-site request forgery (CSRF) attacks exploit the differences in how browsers handle various HTTP methods, influencing the ease of forging requests from a malicious site. The feasibility of such attacks depends on whether the browser can automatically or semi-automatically issue the request without alerting the user, leveraging ambient credentials like . Standard HTML elements facilitate certain methods more readily than others, shaping the risk profile for each . GET requests are particularly susceptible to CSRF because browsers prefetch them implicitly through tags like <img>, <script>, or <iframe>, often without user interaction. This prefetching allows an attacker to trigger a state-changing GET request if the target server mistakenly permits idempotent actions—such as data modification or deletion—to occur via GET, violating HTTP semantics. For instance, early vulnerabilities exploited this by embedding malicious URLs in images, leading to unintended actions on sites that used GET for sensitive operations. Such designs pose risks even for supposedly safe actions, as browsers treat GET as cacheable and non-disruptive. In contrast, POST requests demand more deliberate mechanisms, such as forms or JavaScript-based , requiring some user engagement like form submission to execute. This raises the bar for , as passive embedding (e.g., via images) does not trigger POSTs; however, the remains viable through disguised forms or scripted submissions on malicious pages. Prior to the , browsers offered no built-in restrictions on cross-origin POSTs beyond for scripts, making them a common once GET misuse was recognized. Despite these hurdles, POST's prevalence for state changes keeps it central to CSRF threats. Methods like PUT and DELETE are less prone to CSRF due to limited native browser support; standard HTML forms only accommodate GET and POST, while PUT and DELETE necessitate JavaScript APIs like Fetch or , which browsers restrict via the unless CORS explicitly permits cross-origin access with credentials. Without an overly permissive CORS policy, these requests fail silently or prompt errors, effectively blocking forged invocations from third-party sites. This inherent limitation reduces CSRF risk for RESTful APIs employing such verbs, provided servers enforce method-specific handling. Historically, CSRF vulnerabilities evolved alongside web practices, shifting from GET-dominant exploits in the late and early —when many sites used GET for all actions, enabling trivial attacks via links or embeds—to a POST-centric focus by the mid- as standards emphasized reserving GET for retrieval only. Seminal analyses, such as those examining real-world sites like NYTimes.com, highlighted how undifferentiated handling of methods amplified risks, prompting guidelines to segregate verbs. In modern designs, sensitive operations increasingly avoid unsafe methods like PUT or DELETE for browser-interacted endpoints, favoring or token-based to minimize exposure. JSON-based CSRF represents a variation where attackers target RESTful APIs or endpoints that strictly expect a Content-Type: application/json header, which traditional CSRF techniques using HTML forms or image tags cannot set, as browsers default to application/x-www-form-urlencoded or text/plain for such elements. To exploit this, attackers may leverage server misconfigurations that accept alternative content types like text/plain for JSON payloads, allowing forged requests via simple cross-site elements, or combine it with weak CORS policies that permit credentialed requests from malicious origins. This approach has been demonstrated in real-world scenarios, such as unauthorized payout modifications in financial applications, where the server processed JSON-like data without proper type enforcement. Login CSRF is a specialized variant in which an attacker forges a cross-site request to a target's endpoint using the attacker's own credentials, forcing the victim to authenticate as the attacker without their knowledge. This can expose the victim's subsequent actions under the attacker's account, such as revealing private data or enabling further exploitation, particularly on sites without per-session CSRF tokens on login forms. Unlike standard state-changing CSRF, login CSRF targets unauthenticated users to hijack sessions indirectly, often evading defenses focused solely on authenticated requests. Referrer spoofing relates to CSRF by undermining defenses that rely on validating the header to ensure requests originate from trusted domains. Attackers can spoof the Referer using techniques like malformed URLs in redirects or extensions, though cross-site spoofing without is limited; however, if combined with other vectors, it bypasses header-based checks that fail to account for suppression or alteration in privacy-focused s. notes that Referer validation is unreliable for CSRF prevention due to these spoofing possibilities and inconsistent support. CSRF differs fundamentally from CORS misconfigurations: while CSRF exploits the browser's automatic inclusion of credentials in cross-origin requests to perform unauthorized actions without reading responses, CORS misconfigurations allow unauthorized reading of responses from cross-origin resources but do not inherently enable credentialed writes. Thus, a lax CORS policy might facilitate CSRF by permitting preflighted requests with credentials, but CSRF attacks succeed independently of CORS as long as the target endpoint processes simple requests. Cross-protocol attacks in CSRF contexts historically involved non-HTTP schemes like gopher:// or data: URIs embedded in elements such as images or forms to forge requests outside standard HTTP, but these are deprecated and blocked in modern browsers for reasons, limiting their viability to legacy systems. In modern applications up to 2025, CSRF variations have emerged in web-mobile environments, where postMessage in iframes or windows traditional defenses if validation is absent, allowing malicious sites to trigger authenticated requests across contexts, as seen in vulnerabilities like the Apollo embeddable explorer. Service workers, while primarily for caching and offline functionality, can introduce CSRF risks in apps if misconfigured to intercept and forward cross-origin requests without proper token checks, enabling persistent es in progressive web apps. These twists highlight ongoing evolution, with attackers targeting client-side integrations over pure server-side endpoints.

Impacts and Constraints

Effects on Systems and Users

Successful CSRF attacks can inflict significant harm on individual users by enabling unauthorized actions that leverage their authenticated sessions. For instance, attackers may trick users into initiating financial transactions, such as transferring funds from a or making unauthorized purchases on sites, leading to direct monetary losses. Privacy breaches are also common, where sensitive personal information like email addresses or shipping details is altered without consent, potentially exposing users to further or spam campaigns. Account compromises occur when attackers change passwords, recovery options, or security settings, locking users out and granting persistent access to the assailant. On a systemic level, CSRF exploits erode trust in web applications by demonstrating vulnerabilities in session management, which can discourage user engagement and damage the reputation of affected organizations. These attacks often serve as entry points for more severe chain exploits, such as combining CSRF with (XSS) to bypass protections, steal session tokens, or escalate privileges for broader . In high-privilege scenarios, like targeting administrators, attackers can achieve full control, resulting in data deletion, configuration alterations, or propagation of across the system. Real-world incidents underscore these risks; in 2008, researchers identified CSRF vulnerabilities on major websites, including social networks and financial portals, that could enable attackers to forge actions like adding administrative privileges or altering user profiles, potentially leading to widespread account takeovers. A 2022 study of sites in revealed prevalent CSRF flaws, heightening the risk of fraudulent transactions and financial theft in regions with growing adoption. Broader implications include regulatory non-compliance and operational burdens; for payment processors, failing to mitigate CSRF may violate PCI DSS v4.0.1 Requirement 6.3, which mandates addressing common vulnerabilities including CSRF in secure development processes (effective March 31, 2025), potentially resulting in fines, certification revocation, and elevated transaction fees. Organizations may also face increased support costs for incident response, user notifications, and remediation, exacerbating the financial strain from direct attack damages.

Limitations of CSRF Attacks

Cross-site request forgery (CSRF) attacks inherently fail when the victim is not authenticated with the target application, as the browser will not include valid session or credentials in the forged request, rendering it unauthorized. This requirement limits the attack's scope to scenarios where users maintain active sessions, often expiring after inactivity or logout. Furthermore, applications employing per-request mechanisms, such as unique tokens validated on each submission, block forged requests that lack these elements, preventing successful exploitation. Another key limitation arises from the nature of idempotent operations, particularly those using safe HTTP methods like GET, which are intended solely for data retrieval without modifying server state. Forging such requests may trigger unintended queries but causes no harm, as repeating them yields the same result without side effects. In contrast, state-changing actions via non-idempotent methods like or PUT are the primary targets, but adherence to HTTP standards—recommending GET for reads only—naturally constrains CSRF's potential impact on read-only endpoints. Browser-level protections further restrict CSRF effectiveness. The SameSite cookie attribute, introduced in draft specifications around and standardized in 6265bis, defaults to "Lax" in major browsers starting with 80 in February 2020, followed by , , and . Under SameSite=Lax, s are withheld from cross-site requests using unsafe methods (e.g., ), blocking most CSRF vectors while allowing safe top-level navigations like GET links. For first-party s, approximately 89% effectively adhere to SameSite=Lax or Strict restrictions as of 2024 (HTTP Archive), significantly reducing attack success rates in modern browser environments for such contexts. Despite these mitigations, CSRF persists as a challenge in specific contexts, including legacy systems without updated protections and modern or applications where CORS policies or tokenless endpoints create gaps. For instance, vulnerabilities reported in 2023–2025, such as CVE-2024-20252 in Expressway Series software and CVE-2025-23483 in Universal Analytics Injector plugins, demonstrate ongoing risks in enterprise and third-party integrations, particularly where is inconsistently enforced or clients bypass browser safeguards. Overall prevalence has declined due to widespread adoption and CORS enforcement since the mid-2010s, but these cases underscore limitations in non-browser contexts like API-driven services. CSRF attempts are also relatively easy to detect through server-side of anomalous patterns, such as unexpected or Referer headers indicating cross-site origins, or absent CSRF in requests. These indicators allow teams to identify and block suspicious activity in , further diminishing the attack's stealth and viability. For example, applications monitoring for Referer mismatches can effectively identify many potential forgeries from cross-site origins, enabling proactive defenses when combined with other measures.

Prevention Techniques

Synchronizer Token Pattern

The synchronizer token pattern is a server-side defense mechanism against cross-site request forgery (CSRF) attacks, where the generates a unique, unpredictable for each user session or sensitive request. This , often referred to as a challenge token, is created using a cryptographically secure to ensure it cannot be guessed by an attacker. The associates the with the user's session and embeds it into web forms or requests as a hidden field or custom header, requiring the client to submit it alongside the actual request data for validation. Upon receipt, the compares the submitted against the stored session value; if they match, the request is processed, otherwise it is rejected. This approach leverages session-based to bind the to the legitimate user's , preventing forged requests from malicious sites that lack to the . Implementation involves generating the token on the server during form rendering or prior to sensitive operations, storing it securely in the session store (such as a server-side database or memory cache tied to the session ID), and including it in the HTML as a hidden input field, for example: <input type="hidden" name="csrf_token" value="unique_token_value">. For non-form requests like AJAX, the token can be sent via a custom HTTP header (e.g., X-CSRF-Token) or as a query parameter in GET requests, though POST/PUT/DELETE methods are preferred for state-changing actions. Validation occurs on the server by extracting the token from the request body or header and matching it exactly against the session-stored value before executing any business logic. Frameworks like Spring Security automate this process by integrating token generation and validation into their CSRF modules. This pattern offers several advantages, including high effectiveness against CSRF attacks since the token's secrecy and uniqueness make impractical without session access. It integrates seamlessly with cookie-based without exposing session data to scripts and supports both traditional forms and dynamic requests like . Additionally, it does not rely on browser-specific features, ensuring broad compatibility across user agents. However, drawbacks include the need for server-side , which can introduce challenges in distributed systems due to session across servers. It also requires modifications to application forms and request-handling code, potentially increasing development effort, and may fail if tokens are not properly regenerated after use or if vulnerabilities exist. In high-traffic scenarios, the overhead of token generation and validation can impact performance if not optimized. Best practices, as outlined by OWASP, emphasize using sufficiently long tokens (minimum 128 bits) generated with secure randomness to resist brute-force attacks, ensuring uniqueness per session or per request to prevent replay issues, and implementing token expiration aligned with session timeouts. Tokens should be validated strictly for equality without any normalization, and applications must apply the pattern to all state-changing endpoints while using HTTPS to protect token transmission. For enhanced security, regenerate tokens after successful validation to mitigate certain replay risks, and leverage framework-built implementations to avoid common pitfalls like weak random number generation. The Double Submit Cookie method is a stateless approach to mitigating cross-site request forgery (CSRF) attacks by leveraging token duplication without requiring server-side storage. In this technique, the server generates a cryptographically strong random —typically upon user login or initial page load—and sets it as the value of a sent to the client's . This is automatically included in subsequent requests due to the 's cookie-handling behavior. For state-changing requests, such as form submissions or AJAX calls, the client must submit the same token value in a separate request parameter, often as a hidden form field, query parameter, or custom HTTP header. The server validates the request by comparing the token from the cookie against the one provided in the parameter; if they match, the request is processed, ensuring it originated from a legitimate client session. This mechanism thwarts CSRF because an attacker forging a malicious request from a different site cannot predict or set the random token in the cookie (which requires domain control or XSS), nor can they force the victim's browser to include a matching parameter without knowing the token value. Implementation typically begins with server-side generation of the token using a secure random number generator, followed by setting the cookie with attributes like Secure and SameSite=Strict (though not relying solely on SameSite for protection). On the client side, JavaScript is often used to read the cookie value and populate it into the request—for instance, in a form via a hidden input like <input type="hidden" name="csrf_token" value="readFromCookie()"> or in an AJAX header as X-CSRF-Token: tokenValue. The server then extracts and compares the values on every mutable endpoint, rejecting mismatches. This pattern avoids the need for synchronizing server-stored tokens, making it ideal for distributed or microservices architectures. Key advantages of the Double Submit Cookie method include its simplicity and scalability, as it eliminates server-side state management, reducing database load and enabling easy horizontal scaling for high-traffic applications or . It is particularly well-suited for single-page applications (SPAs) and RESTful services where stateless interactions predominate, and it integrates seamlessly with token-based systems like JWT. Variations may involve subdomain-specific to limit scope or salting the for added , enhancing security in multi-tenant environments. However, the method has notable drawbacks, primarily its vulnerability to cross-site scripting (XSS) attacks; if an attacker injects malicious , it can read the non-HttpOnly (required for client-side access) and forge a valid request by duplicating the token. To mitigate interception, it mandates for all communications, as man-in-the-middle attacks could expose the token in transit. Additionally, improper implementation—such as using predictable tokens or omitting validation on all endpoints—can undermine its effectiveness, and it offers no protection against attacks where the attacker controls setting, like fixation scenarios. The SameSite attribute is a security flag for HTTP cookies that instructs browsers on whether to include the cookie in cross-site requests, thereby mitigating cross-site request forgery (CSRF) attacks by limiting the transmission of authentication cookies in potentially malicious contexts. It accepts three primary values: Strict, which blocks the cookie from being sent in all cross-site requests, ensuring it is only included in same-site navigations; Lax, which permits the cookie to be sent with top-level same-site requests and safe cross-site top-level navigations (such as GET or HEAD methods initiated by user actions like clicking a link), but withholds it from other cross-site subrequests like embedded iframes or images; and None, which allows the cookie to be sent in both same-site and cross-site requests but mandates the Secure attribute to enforce HTTPS-only transmission. This browser-enforced mechanism addresses a core vulnerability in cookie-based authentication, where session cookies could otherwise be automatically attached to forged requests from malicious sites. The concept of SameSite was initially proposed by engineers in a 2013 draft specification to enhance against cross-site threats. It gained traction through implementation in 51 in September 2016, based on an updated draft, and was further refined in subsequent IETF drafts leading to its inclusion in the evolving 6265bis standard for HTTP . Browser adoption accelerated in 2020, with 80 (February 2020) treating unspecified SameSite as Lax by default and requiring None to include Secure for cross-site usage. followed suit, defaulting to Lax in version 83 (November 2020) and enforcing stricter partitioning by version 85 (January 2021), while and achieved similar support around the same period. By 2025, SameSite enforcement is nearly universal across major , including full support in 142+, 145+, and 26+, significantly diminishing reliance on legacy behaviors. Implementation involves setting the attribute in the server's Set-Cookie HTTP response header, such as Set-Cookie: session=abc123; SameSite=Lax; Secure; HttpOnly, which instructs the browser to apply the specified policy without requiring client-side changes. This approach effectively protects against CSRF in scenarios involving third-party content inclusions, like advertisements or embedded widgets, by preventing automatic cookie attachment to cross-site subrequests unless explicitly allowed by or None. Developers must audit existing cookies to ensure compatibility, as unspecified attributes now default to Lax in compliant browsers, potentially breaking cross-site functionalities like federated logins if not adjusted to None; Secure. Despite its strengths, SameSite has limitations that do not fully eliminate all CSRF vectors. It considers requests from subdomains sharing the same registrable domain (e.g., app.example.com and api.example.com) as same-site, allowing potential intra-domain attacks if subdomain isolation is inadequate. Additionally, it does not address non-HTTP mechanisms like postMessage APIs, which can trigger actions without sending cookies, or same-site request forgeries within trusted domains. The None value requires HTTPS, and without it, browsers reject the cookie entirely, complicating legacy HTTP deployments. From 2023 to 2025, updates focused on patching implementation flaws and expanding enforcement, including a March 2023 fix for a vulnerability on devices that allowed SameSite bypass via intent redirects, enabling cross-site cookie leakage in affected versions. These refinements, combined with near-universal support, have substantially reduced CSRF incidence, with studies indicating that Lax or Strict adoption on session s prevents the majority of cross-site forgery attempts in modern web applications.

Client-Side Protections

Client-side protections against cross-site request forgery (CSRF) involve JavaScript-based mechanisms and browser features that enforce additional checks on outgoing requests, ensuring they originate from trusted sources without relying solely on server-side validation. These techniques leverage the (SOP) and (CORS) restrictions to block unauthorized submissions, particularly for requests or form interactions. By requiring non-standard elements like custom headers or origin validations, they prevent attackers from forging requests via malicious sites or embedded content. One common approach is the use of custom HTTP headers, such as X-CSRF-Token, which are appended to requests via JavaScript APIs like XMLHttpRequest or fetch(). Browsers enforce the SOP on requests containing custom headers, preventing cross-site <form> tags or simple cross-origin requests from including them without explicit CORS permission. For instance, developers can override the XMLHttpRequest.open() method to automatically inject the token into a custom header for all AJAX calls, ensuring protection by default across the application. This method raises the bar for attackers, as predicting or forging the header requires same-origin access, which is denied in CSRF scenarios. Modern frameworks integrate these protections natively to simplify implementation. In , the HttpClient module provides built-in XSRF protection through a "cookie-to-header" pattern: a token stored in an XSRF-TOKEN cookie is automatically extracted and sent as the X-XSRF-TOKEN header in non-safe HTTP methods (e.g., POST, PUT). This requires server cooperation to set the cookie but handles client-side token management transparently. Similarly, applications often manage CSRF tokens in component state or context, manually including them in custom headers during API calls with libraries like Axios; while not built-in, this aligns with React's emphasis on explicit state handling for security. Complementing these, Content-Security-Policy (CSP) directives can restrict script sources, indirectly bolstering CSRF defenses by mitigating (XSS) vectors that could steal tokens. Event monitoring via further enhances client-side safeguards by intercepting form submissions or network events to validate request before dispatch. Developers can attach listeners to submit events on forms, checking the window.location.[origin](/page/origin) against an allowlist or the request's Origin header, and aborting suspicious actions. Overriding global fetch or XHR prototypes allows proactive header injection and checks for all asynchronous requests. Additionally, the <meta name="referrer" content="no-referrer"> tag suppresses the Referer header in outgoing requests, reducing information leakage that could aid attackers in crafting targeted CSRF payloads, though it is primarily a tool rather than a direct defense. These techniques ensure dynamic validation without altering logic. In mobile and web hybrid environments, such as Progressive Web Apps (PWAs) or desktop applications, client-side CSRF protections adapt standard web techniques to app-specific contexts. PWAs, built on service workers and web APIs, implement custom headers and origin checks similarly to traditional sites, with added service worker policies to filter network requests. apps, which embed , enforce protections through integration and webview configurations, such as strict CSP to limit cross-origin fetches and overrides for protocol handlers. These hybrids benefit from the underlying browser engine's but require explicit app-level validations to handle native-bridge interactions. Despite their effectiveness, client-side protections have notable drawbacks. They can be entirely bypassed if an XSS vulnerability exists, as injected scripts gain same-origin privileges to read , forge headers, or manipulate events—rendering origin checks moot. Implementation also increases development complexity, requiring consistent integration across frameworks, handling edge cases like third-party scripts, and maintaining token synchronization, which may lead to usability issues or overlooked gaps in hybrid setups. Thus, these methods are most robust when layered with server-side measures.

Additional Server-Side Strategies

Server-side strategies for mitigating cross-site request forgery (CSRF) extend beyond primary and mechanisms by incorporating validation of request , enhanced controls, framework-integrated safeguards, API-specific validations, and layered detection systems. These approaches emphasize server-enforced checks to verify request legitimacy without relying on client-side execution. One effective method involves validating the header to confirm that requests originate from trusted domains. The server examines the Referer to ensure it matches the expected hostname or origin of the application, rejecting requests from untrusted sources. This technique is particularly useful for GET requests or when tokens are unavailable, as it leverages behavior to include the referring page's . However, pitfalls include suppression of the Referer in privacy-focused browsers or modes, such as when users enable "" or navigate from to HTTP pages, and alterations by proxies or corporate firewalls that may strip or modify the header, potentially blocking legitimate traffic. Custom authentication patterns provide additional layers by requiring explicit user verification for sensitive operations. For high-value actions, such as fund transfers or password changes, servers can mandate re-authentication, prompting users to re-enter credentials or complete a secondary before processing the request. This ensures that even if an attacker forges a request using a valid session, the action cannot proceed without fresh user intent. Complementing this, implementing short-lived sessions limits the window of exposure; sessions expire quickly (e.g., after minutes or inactivity), forcing periodic re-authentication and reducing the viability of forged requests during an attack. These measures are recommended for applications handling critical transactions, as they directly counter the automatic credential inclusion in CSRF scenarios. Popular web frameworks incorporate built-in server-side tools to enforce CSRF through and session binding. In , developers can apply to controllers handling state-changing actions, such as limiting requests to 10 per 3 minutes per or session, which throttles potential automated attempts. Similarly, binding session data to client addresses enhances validation by tying the session identifier to the user's remote address, invalidating requests from mismatched IPs and mitigating attacks from compromised networks. supports extensible for similar purposes, where custom implementations can integrate IP-based checks or rate limits via third-party packages like django-ratelimit, ensuring requests align with expected user patterns. These framework features promote scalable, code-level defenses without custom boilerplate. For API endpoints, particularly those using token-based authorization, CSRF prevention leverages protocol-specific claims and scopes. In OAuth 2.0 flows, validating the state parameter—generated server-side and echoed back—ensures requests originate from legitimate redirects, preventing forgery during authentication. JSON Web Tokens (JWTs) incorporate (aud) claims to restrict tokens to specific recipients; servers verify that the token's matches the API's identifier, rejecting mismatched or replayed tokens. Additionally, for anomalous patterns, such as unusual request volumes or geographic mismatches in API calls, allows servers to flag and block potential CSRF vectors in real-time using logging and tools. These techniques are essential for stateless APIs where traditional sessions are absent. Hybrid approaches combine server validations with firewalls (WAFs) for proactive detection. WAFs deploy rules to inspect , using referer checks and behavioral to identify CSRF attempts; for instance, they baseline normal request patterns and block deviations like sudden spikes from external referers. By integrating with server-side logic, such as custom rules for sensitive endpoints, WAFs provide an additional enforcement layer, automatically updating signatures for emerging threats while allowing fine-tuned whitelisting to minimize false positives. This layered strategy enhances overall resilience in distributed environments.

References

  1. [1]
    Cross Site Request Forgery (CSRF) - OWASP Foundation
    Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated ...
  2. [2]
    CWE-352: Cross-Site Request Forgery (CSRF)
    An attacker could trick a client into making an unintentional request to the web server via a URL, image load, XMLHttpRequest, etc., which would then be treated ...<|control11|><|separator|>
  3. [3]
    What is CSRF (Cross-site request forgery)? Tutorial & Examples
    Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not ...
  4. [4]
    Cross-site request forgery (CSRF) - Security - MDN Web Docs
    Oct 17, 2025 · In a cross-site request forgery (CSRF) attack, an attacker tricks the user or the browser into making an HTTP request to the target site from a malicious site.
  5. [5]
    Cross-Site Request Forgery Prevention - OWASP Cheat Sheet Series
    A Cross-Site Request Forgery (CSRF) attack occurs when a malicious web site, email, blog, instant message, or program tricks an authenticated user's web browser
  6. [6]
    Cross-Site Request Forgery (CSRF, XSRF) - Rapid7
    Cross-site request forgery (CSRF) is a web application vulnerability that tricks authenticated users into executing unauthorized actions without their knowledge ...
  7. [7]
    Guide to CSRF (Cross-Site Request Forgery) - Veracode
    Cross-site request forgery, also called CSRF, is a type of web security vulnerability identified as one of the OWASP Top 10 Web Application Security Risks.
  8. [8]
    OWASP CSRFGuard
    OWASP CSRFGuard is a library that implements a variant of the synchronizer token pattern to mitigate the risk of Cross-Site Request Forgery (CSRF) attacks.
  9. [9]
    Things to keep in mind concerning CSRF attacks | Blog - Eclipse Vert.x
    Since then CSRF has had many names such as XSRF, one-click attack, Cross-Site Reference Forgery, session riding, sea surf, hostile linking, “sleeping giant” etc ...
  10. [10]
    [PDF] Hacking Intranet Websites from the Outside (Take 2) - Black Hat
    Aug 1, 2007 · Peter Watkins discovers Client-Side. Trojans, CSRF, pronounces it "sea surf". 2001. Session Riding. Thomas Schreiber discovers CSRF, writes a ...
  11. [11]
    [PDF] Cross Site Request Forgery - ICSI Networking and Security
    The CSRF name was given to them by. Peter Watkins in a June 2001 posting to the Bugtraq mailing list. CSRF flaws exist in web applications with a predictable ...
  12. [12]
    The Cross-Site Request Forgery (CSRF/XSRF) FAQ
    ... CSRF vulnerability. Later in 2001 Peter Watkins posted an entry on the bugtraq mailing list coining the CSRF term in response to another thread titled The ...<|separator|>
  13. [13]
    [PDF] Robust Defenses for Cross-Site Request Forgery
    The authors of RequestRodeo conceptualize CSRF as “Session Riding” and missed login CSRF because there is no “session to ride” when forging a login request ...
  14. [14]
    Cross-Site Request Forgery (CSRF), past and future - Cydrill
    The first well-known exploitation was the MySpace worm by Samy Kamkar in 2005 that combined XSS and CSRF to spread. In 2007 it entered the OWASP Top 10 at 5th ...
  15. [15]
    AJAX and CSRF - Matt Mullenweg
    AJAX and CSRF. August 28, 2005 WordPress ... A good first protection it to use POST for things that change resources, but POSTs can be faked as well, just not as simply as the example I gave above.
  16. [16]
    XSRF/CSRF Prevention in ASP.NET MVC and Web Pages
    May 13, 2022 · Cross-site request forgery (also known as XSRF or CSRF) is an attack against web-hosted applications whereby a malicious web site can influence the interaction.Anatomy Of An Attack · Configuration And... · Antiforgeryconfig
  17. [17]
    [PDF] Security Trend Analysis with CVE Topic Models - Microsoft
    Apparently, the number of CVE entries peaked in 2006 with 6,885 submissions ... Cross-Site Request Forgery (CSRF). 33.1. 18.6. Information Leak. 200.
  18. [18]
    What is CSRF | Cross Site Request Forgery Example - Imperva
    Cross site request forgery (CSRF), also known as XSRF, Sea Surf or Session Riding, is an attack vector that tricks a web browser into executing an unwanted ...
  19. [19]
    What Is CSRF (Cross-Site Request Forgery)? - Palo Alto Networks
    Cross-site request forgery (CSRF) is a web security vulnerability that tricks authenticated users into submitting unintended requests.
  20. [20]
    Is CSRF possible with PUT or DELETE methods? - Stack Overflow
    Aug 6, 2012 · Yes, CSRF is possible with the PUT and DELETE methods, but only with CORS enabled with an unrestrictive policy.What is difference between HTTP methods GET, POST, PUT and ...CSRF protection only for requests with side effect (POST, DELETE ...More results from stackoverflow.com
  21. [21]
    CSRF: A historical dinosaur — But oh so relevant | by Thexssrat
    Feb 10, 2023 · The history of Cross-Site Request Forgery (CSRF) attacks can be ... Schmitz named this type of attack “CSRF,” and it quickly became a ...
  22. [22]
    CSRF in the Age of JSON - DirectDefense
    Sep 22, 2020 · To perform CSRF against a JSON endpoint, we need to either use a different MIME type, exploit a weak CORS policy, or find another means of submitting the ...
  23. [23]
    Exploiting JSON-Based CSRF: The Hidden Threat in Profile ...
    Oct 5, 2024 · This write-up dives into the technical challenges, the critical importance of securing PII, and how an often-overlooked CSRF vulnerability in JSON requests can ...The Challenge of JSON-Based... · The Burp Suite PoC and the...
  24. [24]
    Bypassing Referer-based CSRF defenses | Web Security Academy
    Some applications make use of the HTTP Referer header to attempt to defend against CSRF attacks, normally by verifying that the request originated from the ...
  25. [25]
    What is CORS (cross-origin resource sharing)? - PortSwigger
    Cross-origin resource sharing (CORS) is a browser mechanism which enables controlled access to resources located outside of a given domain.CORS vulnerability with... · Exploiting CORS... · CORS vulnerability with basic...
  26. [26]
    csrf - Is CORS helping in anyway against Cross-Site Forgery?
    Aug 26, 2015 · Generally speaking CORS is not providing greater net benefit because the reason this functionality is available in the first place is due to CORS.Is Cors Helping In Anyway... · 7 Answers · CsrfIs CSRF token vulnerable if CORS is enabled?Cross-Domain Request is a CSRF Attack? (CORS)More results from security.stackexchange.comMissing: misconfigurations | Show results with:misconfigurations
  27. [27]
    CSRF via window.postMessage origin-validation bypass in Apollo ...
    A Cross-Site Request Forgery (CSRF) vulnerability was identified in Apollo's Embedded Sandbox and Embedded Explorer. The vulnerability arises from missing ...Missing: 2024 | Show results with:2024
  28. [28]
    CSRF in 2025: “Solved” But Still Bypassable | by Vivek PS
    sometimes in big-name companies that should know better.Missing: service workers
  29. [29]
    CSRF in 2025: Not Dead, Just Different - Ghost Security
    Aug 19, 2025 · Crypto wallet apps: Attackers used CSRF to silently change default send addresses or drain small amounts by piggybacking on logged-in sessions.Missing: bypass service workers 2024
  30. [30]
    CSRF and XSS: A Lethal Combination - Part I - Infosec Institute
    Feb 20, 2012 · Introduction In the second installment of this series, we discussed one of the most prevalent attacks to applications: SQL Injection.<|control11|><|separator|>
  31. [31]
    CSRF Flaws Found on Major Websites - Dark Reading
    Sep 29, 2008 · Princeton University researchers reveal four sites with cross-site request forgery flaws and unveil tools to protect against these attacks.
  32. [32]
    Vulnerability Analysis of Online Banking Sites to Cross-Site Scripting ...
    (2023) showed how effective it was compared to previous machine learning-based approaches [6]. ... Scenario-Based Cross-Site Request Forgery ...
  33. [33]
    PCI Requirement 6.5.9 – Cross-Site Request Forgery - KirkpatrickPrice
    Oct 13, 2017 · PCI Requirement 6.5.9 states that your organization's applications are protected from cross-site request forgery (CSRF).
  34. [34]
    What is CSRF (Cross-site request forgery) Attacks, Mitigation ...
    The most popular method to prevent Cross-site Request Forgery is to use a challenge token that is associated with a particular user and that is sent as a hidden ...
  35. [35]
    Cookie Legacy SameSite Policies - The Chromium Projects
    ... 2025. ... As of Chrome 80 (see launch timeline), a cookie that does not explicitly specify a SameSite attribute will be treated as if it were "SameSite=Lax".Missing: widespread adoption
  36. [36]
    Cookies | 2024 | The Web Almanac by HTTP Archive
    Nov 11, 2024 · SameSite=Lax : same as SameSite=Strict except that the browser also sends the cookie on navigation to the cookie's origin site. This is the ...
  37. [37]
    Cisco Expressway Series Cross-Site Request Forgery Vulnerabilities
    Feb 7, 2024 · Multiple vulnerabilities in the Cisco Expressway Series could allow an unauthenticated, remote attacker to conduct cross-site request ...Missing: 2023-2025 legacy
  38. [38]
    CVE-2025-23483 : Cross-Site Request Forgery (CSRF) vulnerability ...
    Jan 16, 2025 · CVE-2025-23483 : Cross-Site Request Forgery (CSRF) vulnerability in Niklas Olsson Universal Analytics Injector allows Stored XSS.
  39. [39]
    Is checking the Referer and Origin headers enough to prevent CSRF ...
    Apr 25, 2017 · So to protect against CSRF it is necessary to block any requests that are missing a referer (and origin) header. Edit: This paper has some ...
  40. [40]
  41. [41]
    How To Prevent CSRF Attacks by Using Anti-CSRF Tokens - Invicti
    Dec 15, 2024 · CSRF is a client-side attack that can be used to perform unintended actions within a user session, including redirecting to a malicious website ...Missing: pre- flaw
  42. [42]
    Modern Methods for Cross Site Request Forgery (CSRF) Protection
    Feb 16, 2024 · A dive into different methods to protect against cross site request forgery (CSRF). Including custom headers, signed double-submit cookies, ...Missing: drawbacks | Show results with:drawbacks
  43. [43]
    Lab: CSRF where token is duplicated in cookie - PortSwigger
    This lab's email change functionality is vulnerable to CSRF. It attempts to use the insecure "double submit" CSRF prevention technique.
  44. [44]
    SameSite cookies explained | Articles - web.dev
    May 7, 2019 · Cookies without a SameSite attribute are treated as SameSite=Lax . Cookies with SameSite=None must also specify Secure , meaning they require a ...Use the SameSite attribute to... · Changes to the default...
  45. [45]
    SameSite - OWASP Foundation
    Possible values for the flag are none , lax , or strict . The strict value will prevent the cookie from being sent by the browser to the target site in all ...
  46. [46]
    Cookies: HTTP State Management Mechanism
    Oct 24, 2025 · Using the grammar below, divide the cookie-date into date-tokens. · Process each date-token sequentially in the order the date-tokens appear in ...Table of Contents · Conventions · Server Requirements · User Agent Requirements
  47. [47]
    SameSite Cookie Changes in February 2020: What You Need to Know
    Feb 3, 2020 · Chrome will begin enforcing a new secure-by-default cookie classification system, treating cookies that have no declared SameSite value as SameSite=Lax cookies.Missing: standardized | Show results with:standardized
  48. [48]
    Get Ready for New SameSite=None; Secure Cookie Settings
    Developers must use a new cookie setting, SameSite=None, to designate cookies for cross-site access.Missing: history | Show results with:history
  49. [49]
    Bypassing SameSite cookie restrictions | Web Security Academy
    SameSite cookie restrictions provide partial protection against a variety of cross-site attacks, including CSRF, cross-site leaks, and some CORS exploits. Since ...
  50. [50]
    Chromium bug allowed SameSite cookie bypass on Android devices
    Feb 27, 2023 · A recently patched bug in the Chromium project could allow malicious actors to bypass a security feature that protects sensitive cookies on Android browsers.<|separator|>
  51. [51]
    Preventing CSRF Attacks with the SameSite Cookie Attribute - Invicti
    Aug 22, 2016 · This article explains how the Samesite web cookie attribute works and how it can be used to prevent cross-site request forgery (CSRF) ...
  52. [52]
    Did default SameSite:Lax put the nail in the coffin for CSRF? Mostly ...
    Feb 16, 2022 · If a site uses the “Lax” or “Strict” values for the SameSite attribute when setting session cookies, they can get great CSRF protection with ...Did Default Samesite:Lax Put... · Samesite Attribute · The Gaps<|separator|>
  53. [53]
    How to prevent CSRF vulnerabilities | Web Security Academy
    ### Double Submit Cookie Technique for CSRF Prevention
  54. [54]
    Preventing CSRF Attacks with Anti-CSRF Tokens - Acunetix
    Feb 12, 2025 · To enforce CSRF protection by default, you can override JavaScript's XMLHttpRequest.open() method so that all outgoing requests automatically ...Example Of A Csrf... · How A Csrf Attack Can... · Csrf Protection For...<|separator|>
  55. [55]
    Referer and Referrer-Policy best practices | Articles - web.dev
    Jul 30, 2020 · Don't use referrers for Cross-Site Request Forgery (CSRF) protection. ... referrer policy, and a malicious actor could even spoof the referrer.
  56. [56]
  57. [57]
    XSS vs CSRF | Web Security Academy - PortSwigger
    CSRF tokens do not protect against stored XSS vulnerabilities. If a page that is protected by a CSRF token is also the output point for a stored XSS ...
  58. [58]
    Authentication - OWASP Cheat Sheet Series
    In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information ...Password Storage · Session Management · Multifactor Authentication<|separator|>
  59. [59]
    Spring CSRF Protection Guide: Examples and How to Enable
    This combined with HTTPS and at least one additional mitigation technique (like short-lived session-only cookies) provides adequate protection against CSRF ...
  60. [60]
  61. [61]
    Security considerations — Django Ratelimit 4.1.0 documentation
    Mishandling client IP data creates an IP spoofing vector that allows attackers to circumvent IP ratelimiting entirely.
  62. [62]
    Prevent CSRF Attacks in OAuth 2.0 Implementations - Auth0
    Dec 18, 2024 · Learn how to prevent CSRF attacks from compromising your users when implementing Google OAuth for user registration and user login.Missing: anomalous | Show results with:anomalous
  63. [63]
    JWT Audience Claim: Complete Developer Guide with Examples
    Sep 11, 2025 · Let me walk you through the most common scenarios where audience claims provide real security benefits. The most obvious use case is when you ...Jwt Audience Claim: Complete... · Multi-Audience Jwt Tokens · Audience Claim In Oauth 2.0...Missing: CSRF anomalous
  64. [64]
    7 WAF Security Capabilities and Why You Need Them - Radware
    WAFs combat CSRF by validating requests to ensure they are legitimately initiated by users. Techniques such as token validation and referer header checks are ...