How CSRF works and why it matters
Cross-Site Request Forgery (CSRF) is an attack that tricks a user’s browser into making an unwanted request to a website where the user is authenticated. Because the browser automatically includes credentials like cookies or HTTP authentication headers, the forged request runs with the victim’s privileges. That makes CSRF especially dangerous for operations that change state,transferring money, changing an email address, or toggling account settings,because the attacker leverages the victim’s active session without needing the user’s credentials directly.
Typical attack flow and common vectors
A typical CSRF scenario looks like this: the victim logs into target.example.com and receives a session cookie. The attacker crafts a malicious page and convinces the victim to visit it. While the victim’s browser is on the attack page, it issues a request to target.example.com,perhaps via an auto-submitting html form, an image tag, or a fetch request,causing the target to process a state change under the victim’s session. Attackers rely on browser behaviors that automatically include cookies and other credentials with cross-site requests, which is why APIs and forms are common targets.
Common vectors include simple GET requests embedded as images or script tags, POST requests generated by auto-submitting forms, and, in older or misconfigured APIs, cross-origin json endpoints that accept cookie-based authentication. Single-page applications (SPAs) and APIs that use cookies for session management must be particularly careful because client-side code may interact with many endpoints without explicit CSRF protections.
What makes an application vulnerable
Most vulnerabilities come from three conditions combining: the user is authenticated to the target, the attacker can cause the victim’s browser to make a request, and the server will accept that request as valid because it relies solely on automatically-sent credentials like cookies. Using GET for state changes, lacking CSRF tokens, not validating origin or referer headers, and inconsistent use of SameSite cookie settings increase exposure. APIs that accept cross-origin requests with credentials (Access-Control-Allow-Credentials: true) without strict origin checks also create trouble.
Effective defenses: server-side and client-side measures
Defenses should be layered. The most common and widely applicable protection is the synchronizer token pattern, where the server issues an unpredictable token tied to a session and requires that token for any state-changing request. Tokens should be high-entropy, checked on the server for presence and validity, and ideally rotated or scoped per action when possible. Another strong control is SameSite cookies: setting SameSite=Lax or SameSite=Strict prevents cookies from being sent on many cross-site requests, blocking most CSRF attacks without additional developer changes.
Origin and Referer header checks provide complementary protection. Rejecting requests whose Origin (preferred for POST/PUT/DELETE) or Referer header does not match the expected origin is simple and reliable for modern browsers. Note that some corporate proxies or older clients may strip or alter headers, so use these checks alongside tokens rather than as the only defense. For JSON APIs used by JavaScript front ends, avoid relying on cookies for authentication; instead use tokens sent in custom headers (e.g., Authorization: Bearer) so browsers won’t include them automatically in cross-site requests.
- CSRF tokens (synchronizer token pattern or double-submit cookies)
- SameSite cookie attribute (Lax or Strict)
- Verify Origin and Referer headers for state-changing requests
- Use non-cookie auth (tokens in headers) for APIs when practical
- Avoid side effects on GET requests and enforce POST/PUT/DELETE for changes
Implementation details and trade-offs
CSRF tokens are simple in concept but must be implemented carefully. Generate tokens with secure randomness, store them server-side or as an HMAC tied to the session, and include them in forms and relevant client requests. The double-submit cookie technique places a token in a cookie and also sends it in a request parameter or header; the server verifies both match. This avoids server-side state for tokens but requires secure cookie handling and same-site considerations. Token lifetime should balance security and usability,shorter lifetimes reduce risk but may frustrate users if tokens expire too quickly.
SameSite advantages include minimal developer effort for many applications, but it does not replace token checks in every scenario: older browsers may not support SameSite fully, and some legitimate cross-site flows (third-party integrations) may break if cookies are too restrictive. Origin and Referer checks are low-cost and effective for modern browsers, but they won’t help when certain intermediaries strip headers. When using cors with credentials, ensure Access-Control-Allow-Origin is not a wildcard and only allow trusted origins.
Framework and platform support
Many web frameworks provide built-in CSRF protections: Rails includes authenticity_token in forms, Django has middleware that inserts and validates CSRF tokens, and ASP.NET Core provides anti-forgery tokens out of the box. Use these features rather than rolling your own whenever possible, and read framework documentation to understand how tokens are generated and where to include them in ajax requests. For single-page applications, frameworks often offer recommended integration patterns,store tokens in meta tags or fetch them from a safe endpoint and attach them as headers on state-changing API calls.
How CSRF relates to other threats
CSRF differs from Cross-Site Scripting (XSS) even though they can interact. XSS lets an attacker run script in the victim’s page context and can read tokens, cookies, or DOM elements, which can completely bypass CSRF protections that are exposed to script. That is why removing XSS vulnerabilities is critical: CSRF defenses assume an attacker cannot execute arbitrary JavaScript on the target site. CSRF is also distinct from credential theft,attackers do not need a password, only the ability to induce requests from an authenticated browser.
Practical checklist for hardening against CSRF
Below is a compact list you can apply to reduce CSRF risk across most web applications. Implementing several of these together gives the best protection and helps guard against edge cases and client variability.
- Use CSRF tokens for all state-changing endpoints and include them in AJAX headers or request bodies.
- Set cookies with SameSite=Lax or SameSite=Strict and always use Secure and HttpOnly where appropriate.
- Reject state-changing requests without a valid Origin or Referer header matching your site’s origin.
- Avoid changing state via GET requests and ensure idempotency where possible.
- For APIs, prefer token-based auth in headers rather than cookie-based sessions if clients are non-browser or require cross-origin usage.
- Keep server frameworks and libraries up to date and use built-in CSRF protections when available.
Summary
CSRF is a serious but well-understood threat that exploits automatic browser credentials to trigger actions under a victim’s session. The best defenses combine server-side token validation, secure cookie attributes like SameSite, and origin/referer checks. For APIs, using tokens in headers or strict CORS rules prevents cross-site requests from succeeding. Implement layered protections and fix any XSS issues that could undermine CSRF measures, and rely on framework-provided tools where possible to avoid common pitfalls.
FAQs
Can SameSite cookies fully replace CSRF tokens?
SameSite mitigates many CSRF scenarios and can reduce the need for tokens in simple cases, but it’s not a universal replacement. Older browsers may not support SameSite, and legitimate cross-site integrations may require different handling. Use SameSite as a strong layer, but keep tokens or origin checks for comprehensive protection.
Why are some APIs still vulnerable to CSRF even with CORS configured?
CORS controls whether browsers allow a page to read responses from another origin, but it does not stop a browser from sending cookies with cross-site requests. If an API accepts cookie-based authentication and is configured with Access-Control-Allow-Credentials: true without strict origin validation, attackers can trigger state-changing requests from cross-origin pages. Use strict origin allowlists or switch to header-based tokens to prevent this.
What is the difference between synchronizer tokens and double-submit cookies?
Synchronizer tokens are stored server-side and validated against a user session, ensuring the server can verify token validity. Double-submit cookies send the token both as a cookie and as a request parameter or header; the server checks they match but typically does not need to store the token server-side. Double-submit avoids server storage but requires careful cookie settings and is generally suitable when secure randomness and matching are enforced.
How should SPAs handle CSRF when using cookies for login?
SPAs that rely on cookie sessions should fetch a CSRF token from a safe endpoint or embed it in the initial HTML and send it on each state-changing request as a custom header. Alternatively, use token-based authentication (e.g., JWT in Authorization headers) so the browser will not automatically attach credentials on cross-site requests.



