What Is a CSRF Token? Stopping Forged Requests
A CSRF token is an unpredictable value tied to a user session that proves a state-changing request genuinely originated from your own application.
A CSRF token defends against cross-site request forgery, an attack where a malicious site tricks a logged-in user browser into making an unwanted request to another site. Because the browser automatically sends session cookies, the forged request looks authentic. A CSRF token breaks the attack by requiring a secret value the attacker cannot know.
The attack it prevents
In a CSRF attack, a victim who is logged into a site visits a malicious page that quietly submits a request to that site. The browser attaches the session cookie, so the request appears legitimate. Without protection, the action goes through under the victim identity.
How the token defends
- The server embeds a secret, per-session token in its own forms.
- Legitimate requests include the token; the server verifies it.
- A cross-site forgery cannot read the token, so its request is rejected.
Why it works
The attacker can cause the browser to send a request but cannot read the response from your site, so they cannot learn the token. Requiring that unguessable token on state-changing actions means forged requests fail validation.
CSRF tokens and SameSite cookies
Modern defenses combine CSRF tokens with the SameSite cookie attribute, which limits when cookies are sent cross-site. Together they provide layered protection; relying on only one can leave gaps depending on the browser and scenario.
CSRF protection in CI/CD
If you build web apps, CSRF protection on state-changing endpoints is part of secure coding. Security tests and reviews in your pipeline should confirm that forms and unsafe methods require a valid token before the change reaches production.
Scope of the defense
CSRF tokens protect browser-based, cookie-authenticated flows. APIs authenticated by bearer tokens (the pattern pipelines use) are generally not vulnerable to CSRF, because they do not rely on automatically sent cookies.
Key takeaways
- A CSRF token is an unguessable value proving a request came from your own app.
- It blocks cross-site request forgery on cookie-authenticated, state-changing actions.
- Pair it with SameSite cookies; bearer-token APIs are generally not CSRF-prone.