To prevent CSRF attacks, protect cookie-authenticated writes with your framework’s CSRF controls, validate request origins, and configure SameSite cookies as an additional safeguard. The server must reject forged requests before they change application state.
For a SaaS product, exposed actions can include inviting administrators, changing billing details, or deleting customer data. Cookie-based authentication creates the risk because browsers can attach credentials without the user’s deliberate approval.
Start by identifying which endpoints accept those automatic credentials.
Key Takeaways
- Use built-in CSRF protection and session-bound tokens for cookie-authenticated changes.
- Add exact Origin or Referer validation and appropriate SameSite settings.
- Separate browser sessions, explicitly supplied bearer tokens, and authenticated webhooks because each needs different controls.
- Test rejected requests for actual side effects, not just an error response.
Understand When Browser Sessions Create CSRF Risk
Cookies can authenticate an unwanted request
Cross-site request forgery tricks a browser into sending an unwanted request to an application where the user has an active session. If cookie policies permit, the browser attaches the application’s authentication cookie.
The attacker doesn’t need to read that cookie or the response. The attack succeeds if your server accepts the request and performs the action.
As MDN’s CSRF explanation describes, browsers can send certain cross-origin requests without permission to read their responses. A plain HTML form can therefore threaten an unprotected write endpoint.
CSRF and XSS cross different boundaries
Cross-site scripting (XSS) runs attacker-controlled JavaScript inside your application’s origin. CSRF usually starts outside that origin and abuses the browser’s authenticated access.
This distinction affects defenses. A CSRF token blocks an external attacker who cannot obtain it. However, injected JavaScript inside your application may read the token or submit authenticated requests directly.
Keep output encoding, safe rendering, and other XSS protections alongside CSRF defenses. Neither category replaces the other.
Prevent CSRF Attacks With Framework Protections
Enable your framework’s CSRF middleware before writing a custom implementation. For example, Django provides CsrfViewMiddleware. Centralized protection reduces the chance that a new route ships without validation.
Apply protection to state-changing requests, including POST, PUT, PATCH, and DELETE. Keep GET, HEAD, and OPTIONS free of user-requested state changes.
Use synchronizer tokens for server-side sessions
A synchronizer token is an unpredictable secret associated with the user’s session. Your server issues it to the legitimate application, then requires it on subsequent writes.
Generate tokens with a cryptographically secure random generator. Store the expected value in the session and deliver it through rendered HTML or a same-origin response. Forms submit it through a hidden field; JavaScript can send it in a custom header.
Validate the submitted value against the session before business logic runs. Reject missing or invalid tokens, normally with a 403 response.
OWASP’s CSRF prevention guidance recommends this pattern for stateful applications. Keep tokens out of URLs, logs, and analytics because those systems can expose them.
Choose signed double-submit tokens for stateless designs
A double-submit design places a token in a cookie and requires the client to echo a corresponding value in a request header or body.
Avoid a naive equality-only implementation. An attacker who can inject cookies may defeat it.
Instead, use a signed token bound to the authenticated session. Validate both its cryptographic integrity and session binding. Prefer a maintained framework implementation over a custom signing format.
Validate Origin and Referer Against Trusted Configuration
For browser-based writes, compare the Origin header with your application’s approved origins. An origin includes the scheme, hostname, and port, but no path.
Use parsed, exact comparisons. Substring matching can accept an attacker’s hostname containing your trusted domain’s text. Also, never reflect an arbitrary supplied origin as approved.
When Origin is absent, validate the origin portion of Referer where appropriate. Frameworks may already implement this behavior. Django, for example, performs strict Referer checking for HTTPS requests without an Origin header.
For browser-only writes, reject requests when neither header establishes an approved origin. Handle legitimate exceptions through an explicit policy rather than silently trusting missing or null values.
Behind a reverse proxy, derive the expected origin from trusted configuration. Only trust forwarded host information from infrastructure you control.
These checks supplement token validation and help catch deployment mistakes.
Configure SameSite Cookies Without Overestimating Them
SameSite controls when browsers attach cookies to cross-site requests. Set it explicitly on session cookies rather than depending on browser defaults.
SameSite=Lax permits cookies on ordinary cross-site, top-level navigations using safe methods, such as following a link. It generally withholds them from cross-site form submissions using POST.
SameSite=Strict is more restrictive, but it can interrupt expected behavior when users arrive through external links. Meanwhile, SameSite=None permits cross-site cookie use and requires Secure. Browser third-party-cookie restrictions can still block those cookies.
MDN’s Set-Cookie documentation explains these attributes and their interaction. Also apply Secure and HttpOnly to session cookies, and keep their domain scope narrow.
HttpOnly prevents JavaScript from reading a cookie. It doesn’t stop the browser from sending that cookie with a forged request.
Same-site and same-origin are different boundaries. A compromised sibling subdomain can be same-site while remaining cross-origin, so SameSite alone doesn’t establish trust.
Keep CSRF tokens and origin validation even when your cookie settings appear restrictive.
Handle SPAs and APIs According to Their Credentials
Send CSRF tokens with cookie-authenticated SPA writes
A single-page application still needs CSRF protection when its backend authenticates requests through cookies.
Retrieve the token through a same-origin page or dedicated endpoint. Then attach it to state-changing requests using your framework’s expected header, such as Django’s X-CSRFToken.
Limit token attachment to approved API destinations. A global HTTP interceptor mustn’t send the token to unrelated third-party services.
For cross-origin cookie requests, Fetch generally needs credentials: "include". The API must return an explicit approved Access-Control-Allow-Origin value and Access-Control-Allow-Credentials: true.
Return the required permissions on preflight responses when applicable and on actual responses. Explicitly allow the required methods and headers, including the CSRF header. A wildcard origin doesn’t work with credentialed CORS.
Cross-origin cookie access also remains subject to SameSite and browser cookie policies.
Distinguish bearer authentication from browser cookies
An API that accepts only an explicitly supplied Authorization: Bearer token generally avoids classic cookie-based CSRF. A malicious page cannot automatically attach a bearer token it doesn’t possess.
However, a JWT stored in an automatically attached cookie creates the same CSRF concern as other authentication cookies. Token format doesn’t determine exposure.
If an endpoint accepts bearer authentication and cookie-session fallback, protect its cookie-authenticated path.
CORS controls browser access to responses, not every request reaching your server. As MDN’s practical CSRF guidance explains, browser request behavior matters when choosing defenses. CORS alone isn’t a replacement for CSRF protection.
Keep Webhook Exemptions Narrow and Authenticated
Incoming webhooks are server-to-server requests. They normally cannot obtain a user’s session-bound CSRF token, so dedicated webhook endpoints often need an exemption from browser CSRF middleware.
Replace that browser-specific control with webhook authentication. Follow the sender’s signing scheme, validate signatures against the original request bytes, and reject failures before changing subscriptions or sending messages.
Apply replay protection according to the sender’s protocol. Also make event processing idempotent so legitimate retries don’t repeat a business action.
Keep exemptions limited to dedicated routes. Never disable protection across an entire API merely because one webhook endpoint cannot submit a CSRF token.
A webhook route should not fall back to browser session cookies as proof of authorization.
Test Rejection Paths and Avoid Common Shortcuts
CSRF middleware configuration is only useful if it covers the deployed request path. Test through your normal proxy and authentication layers, including any route-specific exemptions.
Run these tests against an environment you control:
- Submit writes with no token, an altered token, and a token from another session. Each attempt must fail before business logic executes.
- Submit an HTML form from a separate test origin. Exercise form-encoded, multipart, and text payloads wherever endpoints accept them.
- Send writes with an unapproved Origin, a misleading hostname, and missing origin information. Confirm your documented rejection policy applies.
- Exercise successful forms and SPA requests, including multiple tabs and session renewal. Security controls must preserve legitimate workflows.
- Inspect stored data, queued jobs, outgoing messages, and audit events after rejected requests. An error response alone doesn’t prove nothing happened.
Don’t rely on JSON request bodies without enforcing the expected content type and parser behavior. Likewise, switching an action to POST doesn’t itself prevent CSRF attacks.
Never disable middleware globally to resolve a frontend error. Fix token delivery, trusted-origin settings, or credential configuration instead.
Log safe failure categories and request identifiers, but redact tokens, cookies, and authorization values.
Frequently Asked Questions
Do login forms need CSRF protection?
Yes. Login CSRF can place a victim in an attacker-controlled account, after which the victim may unknowingly add sensitive information to that account.
Protect the login submission using your framework’s supported pre-authentication CSRF mechanism. After successful authentication, replace the pre-login session rather than promoting its identifier unchanged.
Does a valid CSRF token authorize tenant access?
No. A valid token helps establish that a request came through an authorized browser context. It doesn’t grant permission to access a workspace or change another tenant’s data.
Authenticate the user, validate CSRF protections, and enforce tenant membership and action permissions separately. None of those checks substitutes for the others.
Build CSRF Protection Into Every Browser Write
Reliable CSRF prevention starts with understanding which credentials the browser sends automatically. For cookie-authenticated applications, use framework-managed tokens, origin checks, and carefully chosen cookie settings together.
Keep browser writes, bearer-token APIs, and webhooks on clearly defined authentication paths. Before releasing changes, prove that forged requests leave application state untouched.