# CSRF Explained: Tokens, SameSite Cookies, Origin Checks, and Safe Testing

Canonical: https://vulnify.app/blog/csrf-tokens-samesite-origin-checks

Learn how CSRF works, when cookie-authenticated applications are exposed, and how tokens, SameSite cookies, Origin checks, reauthentication, and safe testing work together.

Cross-Site Request Forgery, or CSRF, happens when a browser is tricked into sending a state-changing request to a site where the victim is already authenticated. The attack works because browsers automatically attach some credentials, especially cookies, to requests. If the application accepts the request without verifying that it came from the intended user interaction, an attacker may be able to make the victim's browser perform an action the attacker could not perform directly. CSRF is easy to confuse with CORS because both involve cross-origin behavior, but they solve different problems. CORS controls whether browser JavaScript may read certain cross-origin responses. CSRF defenses control whether a state-changing request should be accepted in the first place. This guide explains token patterns, SameSite cookies, Origin checks, common mistakes, and a safe way to validate protections. The CSRF attack model Imagine a banking application that uses a session cookie. A logged-in user visits an unrelated malicious page. That page submits a form to the banking site. If the browser attaches the user's session cookie automatically and the banking application accepts the request without an anti-CSRF control, the action may run as the victim. Victim logs in to trusted.example | v Browser stores authenticated session cookie | v Victim visits attacker.example | v Attacker page sends state-changing request to trusted.example | v Browser may attach trusted.example cookies | v Server must decide whether the request is legitimate The attacker does not necessarily need to read the response. If the goal is to change an email address, add a payment destination, or perform another state-changing action, the request itself can be enough. What conditions usually make CSRF possible? The application uses credentials that the browser sends automatically, commonly cookies. A state-changing endpoint accepts a request without a strong anti-CSRF check. The attacker can predict or construct the required request parameters. The victim is authenticated when the malicious request is sent. Applications using explicit bearer tokens stored outside ambient browser cookie behavior can have a different CSRF risk profile, but they still need secure token storage and protection against XSS. Security design should consider the complete authentication model rather than applying one universal rule. Synchronizer tokens One common defense is a cryptographically strong token associated with the user's session. The server places the token in a legitimate form or page and requires the same value on the state-changing request. An attacker on another origin should not be able to read the token from the victim's protected page. &lt;form method="post" action="/account/email"&gt; &lt;input type="hidden" name="csrf_token" value="random-session-bound-value"&gt; &lt;input type="email" name="email"&gt; &lt;button type="submit"&gt;Update&lt;/button&gt; &lt;/form&gt; The server must validate the token before changing state. A token present in the page but ignored by the backend provides no protection. Double-submit cookie patterns Some applications use a value in a cookie and require a matching value in a request parameter or header. Implement this carefully and follow established framework guidance. Naive designs can be weakened by subdomain cookie injection, weak token generation, or comparison mistakes. If your framework provides a mature CSRF mechanism, prefer using and correctly configuring it rather than inventing a custom token format. SameSite cookies are valuable defense in depth The SameSite cookie attribute can reduce when browsers send cookies in cross-site contexts. Strict , Lax , and None have different compatibility and product implications. An authentication cookie used in a standard first-party application may be able to use a restrictive setting, while federated identity, embedded payments, or cross-site integrations may need different behavior. Do not choose a SameSite value blindly. Test login, logout, payment, SSO, and embedded flows. If SameSite=None is required, the cookie must also be marked Secure in modern browsers. Use the Vulnify Cookie Security Checker to inspect the attributes delivered by the public application. Origin and Referer validation Servers can inspect the Origin header on many state-changing requests and reject requests from unexpected origins. When Origin is unavailable, a carefully implemented Referer check may provide additional evidence. These checks should compare complete trusted origins and account for the application's real proxy and deployment architecture. Do not use loose substring matching. An origin such as https://trusted.example.attacker.test is not the same as https://trusted.example . Custom request headers can help API designs JavaScript API clients often send a custom anti-CSRF header. Cross-origin requests with custom headers normally trigger CORS preflight, which adds another control point. The server should still validate the token or trusted request property and maintain a narrow CORS policy. This is where CORS and CSRF interact without becoming the same control. The CORS Checker can help inspect public CORS behavior, while the application still needs explicit request-forgery defenses for authenticated state changes. Do not use GET for meaningful state changes GET requests are expected to be safe and idempotent from the perspective of normal web architecture. They can be triggered easily through links, images, crawlers, prefetchers, and third-party content. Avoid designs where visiting a URL changes a password, deletes data, enables an integration, or performs another security-sensitive action. Using POST instead of GET does not by itself solve CSRF, but it creates a more appropriate place to apply token, Origin, and authorization checks. XSS can defeat many CSRF defenses If an attacker can execute JavaScript in the trusted origin, they may be able to read anti-CSRF tokens from the page and submit legitimate-looking requests. This is why CSRF protection does not replace XSS prevention, and XSS remediation should remain a priority. Security controls are layered. SameSite, tokens, Origin checks, CSP, output encoding, authentication, and authorization each address different failure modes. Hypothetical scenario: email change without a token A SaaS application uses a session cookie and exposes POST /account/email . The request contains only the new email address. The backend checks that the session is authenticated but does not validate a CSRF token or Origin. An attacker hosts a hidden form on another website that submits to the endpoint. A logged-in victim visits the attacker's page and the browser sends the SaaS session cookie with the form submission. The application accepts the request because it sees a valid session. A better design requires a server-validated anti-CSRF token, uses an appropriate SameSite session policy, checks request origin for sensitive actions, and may require reauthentication before changing high-impact account information. The email-change workflow should also notify the existing address so unauthorized changes are easier to detect. How to test CSRF safely 1. Identify state-changing actions List profile updates, password or email changes, payment settings, API key creation, role changes, deletion, uploads, and administrative actions. Focus on endpoints where a forged action would matter. 2. Inspect how authentication is carried Determine whether the browser automatically attaches cookies and how those cookies are scoped. Review SameSite , Secure , Domain, and Path attributes. 3. Inspect the request defenses Look for anti-CSRF tokens, required custom headers, Origin checks, and reauthentication. Confirm the backend rejects missing or invalid values rather than only placing them in the frontend. 4. Use test accounts and harmless actions Perform validation only on applications you own or are authorized to test. Prefer a staging environment and actions that do not affect real users. A harmless profile preference is safer than testing a financial transaction. 5. Retest after authentication changes SSO, cookie changes, reverse proxies, new frontend origins, and framework upgrades can alter CSRF behavior. Repeat the test when the authentication architecture changes. Common CSRF mistakes Assuming CORS prevents CSRF. Using a token in the form but not validating it server-side. Using predictable or static tokens. Applying CSRF protection only to selected sensitive endpoints while missing other state-changing routes. Relying solely on SameSite without testing required cross-site flows. Using loose Origin matching. Allowing GET requests to change state. Forgetting administrative and API endpoints. Disabling framework CSRF protection globally to fix one integration. How Vulnify fits into CSRF-related review Vulnify can help with public controls surrounding a CSRF design. The Cookie Security Checker reviews supported cookie attributes, the CORS Checker examines cross-origin policy, and the Website Security Scanner provides broader public-surface coverage. CSRF protection itself often depends on authenticated application workflows and server-side token validation. A public scan cannot prove every state-changing route is protected. Combine external checks with framework configuration review, authenticated testing, and secure code review. CSRF defense checklist Identify every meaningful state-changing route. Use framework-supported CSRF protections when available. Validate tokens server-side. Set session SameSite policy deliberately. Use Secure cookies over HTTPS. Validate trusted origins on sensitive requests. Keep CORS allowlists narrow. Avoid state changes over GET. Require reauthentication for critical account changes when appropriate. Retest after SSO, cookie, proxy, or frontend changes. CSRF in modern single-page applications Single-page applications do not automatically eliminate CSRF. The determining factor is how the browser authenticates requests. If a SPA relies on cookies that are attached automatically, state-changing API requests can still need CSRF defenses. If authentication is carried in an explicit authorization header that an attacker cannot cause the browser to attach cross-site, the threat model is different. Document the authentication mechanism for each API instead of applying one rule mechanically. Hybrid applications often use both cookies and bearer tokens across different routes, which means one endpoint may require CSRF protection while another does not. Conclusion CSRF is fundamentally about whether the server can distinguish a request the user intended from one their browser was tricked into sending. Strong defenses combine server-validated tokens, appropriate SameSite cookies, Origin checks, secure authentication design, and careful handling of state-changing routes. Keep CORS and CSRF conceptually separate, test the real authenticated workflow, and use layered controls so one browser behavior change does not become an account-level security failure.
