A CSRF token is a secret, unpredictable value that a server embeds in a page and requires back with every state-changing request, so it can tell a request from its own page apart from a forged one sent by another site. An attacker's page can make your browser send cookies, but it cannot read the token, so the forged request fails the check.
This article is about the token itself: how it is made, where it travels, and what breaks it. For the attack it stops, see what CSRF is.
What does a CSRF token do?
Browsers attach cookies to a request based on where it is going, not on which page started it. A session cookie therefore proves that a request comes from your browser, but not that you meant to send it. The token closes that gap. MDN describes the flow this way: when the server serves a page, it embeds an unpredictable value in the page. When the legitimate page sends the state-changing request, it includes the token. The server carries out the request only if the token matches.
The attacker's page has no way to learn the value. The browser's same-origin policy stops it reading your site's HTML, so its forged form carries a missing or wrong token and the server rejects it.
How the server creates and checks it
The standard design is the synchronizer token pattern. OWASP lists three required properties: the token must be unique per user session, secret, and unpredictable (a large random value from a secure random generator). It says tokens should be generated on the server side, and it allows either one token per session or a new one for each request. Per-request tokens are described as more secure, but they can cause usability problems, for example when a user opens the same form in two tabs and the older token stops working.
The check is simple:
- The server creates a random token and stores it, usually in the user's session.
- It writes the token into each page that can send a state-changing request.
- When a POST, PUT, PATCH or DELETE arrives, it compares the submitted token with the stored one.
- If the token is missing or does not match, it rejects the request. OWASP: the request should be rejected if the token was not found within the request.
Where the token goes in the request
In a form
For ordinary forms, the token is a hidden field, so the browser sends it back automatically on submit. MDN describes this as the usual approach for form submissions:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="6f1c2b9e8a...random...">
<input type="text" name="amount">
<button type="submit">Send</button>
</form>
The field name and value above are an example. Your framework picks its own name.
In a JavaScript request
For fetch() and similar APIs, MDN says the token might be placed in a cookie or embedded in the page, and the JavaScript extracts it and sends it as an extra header. OWASP calls a custom header more secure than a hidden form field. Django's documentation shows this pattern with an X-CSRFToken header:
const request = new Request(url, {
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin' // do not send the token to another domain
});
fetch(request);
The mode: 'same-origin' line matters: never send your token to a different domain.
What not to do
- Do not put it in the URL. OWASP warns that a token must not leak into server logs or URLs, and notes that GET requests can leak tokens through browser history, logs and Referer headers. State changes should not be GET in the first place.
- Do not rely on a cookie alone. OWASP says a token should not be transmitted in a cookie for synchronizer patterns, and that validating only a cookie is insecure. The token must also arrive in a header or form field.
Using it in a framework
MDN advises using the CSRF support built into your web framework rather than writing your own. In Django, put the template tag inside every POST form that targets your own site:
<form method="post">{% csrf_token %}
...
</form>
The tag renders a hidden input that Django's CsrfViewMiddleware checks. Django's documentation warns not to use it in forms that target external URLs, since that would leak the token. By default the token cookie is named csrftoken (changeable with CSRF_COOKIE_NAME). If a request fails the check, the default response is 403 Forbidden, and the failure is logged as a warning to the django.security.csrf logger.
Django also advises enabling the middleware and exempting only specific views with csrf_exempt, rather than switching the middleware off and protecting views one by one. An exempt view is then unprotected, so keep the list short.
The stateless variant: signed double-submit cookie
If you do not want to store tokens on the server, OWASP recommends the signed double-submit cookie. The server sends the token in a cookie and also requires it in a header or form field, and checks that the two match. What makes it safe is the signature. The token is an HMAC (OWASP specifies HMAC-SHA-256 over an unambiguous encoding) of a value tied to the user's authenticated session plus a random value, computed with a server-side secret key. OWASP lists these rules:
- Tie the token to the authenticated session. Signing without session binding provides minimal protection.
- Compare with a constant-time comparison function.
- Read the token from a header or form field, never from the cookie alone.
- Generate a new token when a new session starts.
- Set the cookie with the
Secureattribute. OWASP also suggests the__Host-prefix, which stops other subdomains overwriting the cookie:
Set-Cookie: __Host-token=RANDOM; path=/; Secure
The naive version, where the server just compares a cookie to a form value with no signature, is discouraged. OWASP says an attacker who can write cookies on your domain, for example through a compromised subdomain, can bypass it.
Why a token can still fail
| Mistake | Result |
|---|---|
| Token is predictable (counter, timestamp, user ID) | The attacker guesses it and forges a valid request |
| Token in the URL | Leaks through logs, history and Referer headers |
| Token only checked when present | The attacker simply omits it |
| Token sent to a third-party site | That site can replay it |
| Unsigned double-submit cookie | Defeated by cookie injection from a subdomain |
| XSS on your own site | Script reads the token from the page and sends it |
The last row is the one OWASP stresses: XSS can defeat all CSRF mitigation techniques. A token is no substitute for fixing cross-site scripting.
Tokens are one layer
OWASP now names the Sec-Fetch-Site request header as the primary signal for CSRF protection, with an origin check as a mandatory fallback for browsers that do not send it. SameSite cookies add another layer. A token remains the most common method for form-based sites, and MDN names it the first primary defence, but it works best combined with the others.
If every POST returns 403
After you turn on CSRF protection, a 403 on every POST usually means the token is not reaching the server. Check the request in the browser's network tab and look for these causes:
- The template did not render the hidden field.
- JavaScript is not copying the token into the header name the framework expects.
- A cached page is serving an old token after the session changed.
- The form posts to a different domain, which the protection is designed to block.
Fix the cause. Do not disable the check to make the error go away.
Frequently asked questions
- Is a CSRF token the same as a session token or API key?
- No. A session ID proves who you are and is sent automatically as a cookie. A CSRF token proves that a request came from a page your site served. OWASP puts it plainly: a CSRF token is not an access token.
- Should a CSRF token go in the URL?
- No. OWASP says a token must not be leaked in server logs or in the URL. URLs end up in browser history, logs and Referer headers, so state-changing requests should be POST with the token in a hidden field or a header.
- Does a CSRF token protect against XSS?
- No, and XSS defeats it. Script running inside your own origin can read the token from the page and send it. Fix XSS separately.
- Do I need a CSRF token if I use SameSite cookies?
- OWASP and MDN treat SameSite as an extra layer, not a replacement. Use a token or a Sec-Fetch-Site check as the main defence.