What Is CSRF? Preventing Unwanted Requests from Signed-In Users
Cross-site request forgery (CSRF) is an attack in which another site causes a browser to send an unwanted state-changing request to a site where the user is signed in. The browser may attach the session cookie automatically, so checking that cookie alone does not prove that the user intended the action. The core defenses are to require an unpredictable CSRF token or validate trusted request-origin signals on every state-changing path, and to ensure safe methods such as `GET` never change server state.
Why can automatic browser credentials cause a problem?
When a browser is already signed in to a site, it may automatically attach that site's session cookie to requests sent there. A site controlled by an attacker can try to make the victim's browser send a request to the target site. The request then arrives through the browser with a valid session. If the server checks only the session cookie and does not also validate intent or request context, it may perform an action the user did not ask for.
Consider a hypothetical calendar service that lets a signed-in browser change notification settings. If a different site tricks the browser into sending a request to that service, the browser includes the session cookie, and the server has no forgery check beyond that cookie, the setting could change without the user's intent. Because of the same-origin policy, an attacker generally cannot freely read the target site's response. The key CSRF risk is making an authenticated browser perform an unwanted action, not stealing the response. MDN explains the role of automatically sent session information and forged state-changing requests.
CSRF risk commonly requires several conditions together:
The request relies on credentials the browser sends automatically, such as cookies or browser-managed HTTP authentication.
The request changes server state.
An attacker can learn the normal request address and predict its parameters.
The server does not require a separate defense to establish that the request came through an allowed application flow.
How does a token check intent?
A CSRF token is an unpredictable value issued by the server and sent with a state-changing request from a legitimate page. The server checks the submitted value against the token expected for that session or request context, and rejects a missing or mismatched token. It differs from an authentication cookie: the browser may send a cookie automatically, but an attacker from another origin should not be able to read the legitimate page's token.
For server-rendered forms, a common pattern is a synchronizer token in a hidden field that the server validates on submission. A JavaScript API can send a token provided to the page in a custom header such as X-CSRF-Token. Prefer the framework's supported protection and verify that it covers every state-changing route. Avoid putting tokens in URLs, where they can leak into browser history, logs, or referrer data. Token lifetime and renewal should follow the framework's session and usability model; single-use tokens are not automatically the right choice for every application.
The double-submit cookie pattern also compares a token in a cookie with one sent in the request, but a naive implementation can be vulnerable to cookie injection through a compromised sibling subdomain or weak cookie configuration. For new code, follow a reviewed signed, session-bound pattern or the framework's current guidance; do not rely only on checking that a cookie and request value are equal. OWASP discusses synchronizer tokens, double-submit patterns, custom headers, and implementation cautions.
What do Origin and Fetch Metadata checks add?
For state-changing requests, a server can compare the Origin header with a trusted list of its own origins. Referer can be a secondary signal, while accounting for privacy settings and proxies that may remove or alter headers. A service behind a proxy should not blindly trust incoming Host or X-Forwarded-Host values. Forwarded host data may be used to determine the target origin only when trusted proxies are configured to overwrite client-supplied values. Maintain explicit trusted origins and do not treat a missing or literal null origin as an automatic exception for sensitive actions.
Modern browsers can send Fetch Metadata headers. Sec-Fetch-Site tells the server whether a request is same-origin, same-site, or cross-site; a policy can reject clearly cross-site state-changing requests. Plan a fallback for older clients, stripped headers, and legitimate integrations, and document exceptions. same-site is broader than same-origin: it can include another subdomain under the same registrable domain. If every sibling subdomain is not trusted, do not automatically treat all same-site requests as safe.
Are SameSite cookies or CORS enough by themselves?
The SameSite cookie attribute limits when browsers attach cookies to cross-site requests. Strict withholds cookies on some legitimate navigation from external sites and can harm usability. Lax may still send cookies on top-level safe-method navigation, so a state-changing GET can defeat the intended protection. None allows cross-site use and requires Secure. Browser behavior and application flows vary, so set the attribute explicitly and verify the actual behavior.
Use methods whose semantics match state changes, such as POST, PUT, PATCH, or DELETE, and keep GET, HEAD, and OPTIONS free of server-side state changes. Otherwise a link, preview, or top-level navigation allowed with SameSite=Lax could trigger an action. SameSite is scoped to a site rather than an origin, so a compromised sibling subdomain under the same registrable domain may still be treated as same-site.
CORS controls whether a browser script from another origin may read a response; it does not prevent every cross-origin request from reaching the server. A simple HTML form request can reach the server without a preflight. The server can process it even when the browser prevents the other site from reading the response. Requiring a custom header on JavaScript API requests can use CORS preflight, but credentialed origins must be tightly allowlisted and the configuration must be checked. OWASP's CORS guide explicitly states that CORS does not prevent CSRF.
| Defense | Main role | Limit when used alone |
|---|---|---|
| CSRF token | Validates a value known to the legitimate application flow | Gaps remain if any state-changing path skips validation |
| Origin/Referer check | Confirms the initiating web origin is trusted | Requires a policy for missing headers, proxy behavior, and legitimate integrations |
| Fetch Metadata | Adds browser-reported site context for the request | Needs fallback behavior for absent headers and care with sibling subdomains marked same-site |
| SameSite cookie | Withholds authentication cookies on some cross-site requests | Safe-method navigation, subdomains, and compatibility prevent it from replacing full request validation |
| CORS | Controls cross-origin response reading | Does not stop simple requests from being processed by the server, so it is not a CSRF defense |
A safe review and implementation sequence
The following defense-focused process is for an application owner or authorized reviewer working in their own test environment.
**Inventory state changes.** Find forms and APIs that use session cookies and record which data or permissions they change. Pay special attention to any supposedly safe `GET` that changes state.
**Separate authentication from intent.** A valid login cookie identifies a session; it does not prove that the user intended a particular request. Check that each state-changing route requires a server-validated token or strict origin policy.
**Use the framework's supported CSRF protection.** Cover server-rendered forms, asynchronous requests, mobile web views, multiple subdomains, and external APIs. Limit intentional cross-origin integrations by endpoint-specific allowlists, necessary authentication, and logging.
**Layer defenses.** Set suitable `SameSite`, `Secure`, and `HttpOnly` cookie attributes. Where appropriate, use `Origin` and Fetch Metadata checks to restrict cross-site state-changing requests. Do not rely on SameSite alone or assume all subdomains are equally trusted.
**Test negative and legitimate cases with isolated data.** Missing or incorrect tokens, untrusted origins, and disallowed methods should be rejected by the server without changing data. Normal application forms and APIs should still work; external links or integrations needed for usability should follow documented exceptions.
**Verify failure handling and recovery.** Review missing Fetch Metadata or Origin headers, login forms, proxy paths, old sessions, and expired tokens. When a request is blocked, have the user obtain a fresh token through the normal page and retry; do not disable CSRF validation as a workaround. Keep session tokens and sensitive input out of logs.
The OWASP Web Security Testing Guide describes reviewing authenticated state-changing requests and their CSRF controls. Test only in an authorized non-production environment or with isolated accounts; do not alter real users' transactions, settings, or records.
Common misconceptions
**“CORS blocks CSRF.”** CORS may block response reading while a simple request is still processed by the server.
**“POST is automatically safe.”** POST can still be forged without a token or origin validation. A safe HTTP method means it should not change state; it does not mean every request using that method is trustworthy.
**“SameSite=Lax is enough.”** Review state-changing GET routes, sibling-domain trust, and browser behavior separately.
**“Authentication proves user intent.”** A session cookie identifies the user; it does not prove which site initiated the request or that the user intended it.
**“CSRF steals a password or cookie.”** Usually it abuses credentials the browser already sends so the server performs an unwanted action.
References
OWASP Cheat Sheet Series, [Cross-Site Request Forgery Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
OWASP Web Security Testing Guide v4.2, [Testing for Cross Site Request Forgery](https://wstg.owasp.org/v4.2/4-Web_Application_Security_Testing/06-Session_Management_Testing/05-Testing_for_Cross_Site_Request_Forgery/)
OWASP Cheat Sheet Series, [CORS Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/CORS_Security_Cheat_Sheet.html)
MDN, [Cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)