If you’ve ever dug into web security or looked through the source code of a login form, you’ve probably noticed a hidden field with a long, random-looking string tucked inside it. That’s a CSRF token — and while it might seem like a minor implementation detail, it’s one of the unsung heroes of web application security. In this post, we’ll break down exactly what CSRF tokens are, why they exist, and how they protect both you and your users.
First, What Is CSRF?
CSRF stands for Cross-Site Request Forgery. It’s a type of attack where a malicious website tricks a user’s browser into making an unwanted request to a different website — one where the user is already authenticated.
Here’s a simple scenario to make it concrete:
- You log in to your online banking portal. Your browser stores a session cookie that authenticates you.
- Without logging out, you visit a different website — perhaps a dodgy link shared in an email.
- That malicious page contains hidden code that silently sends a request to your bank’s server — say, a request to transfer £500 to an attacker’s account.
- Because your browser automatically attaches your banking session cookie to any request made to the bank’s domain, the server has no obvious reason to distrust it. As far as the bank’s server is concerned, you made that request.
This is the essence of CSRF: the attacker doesn’t need to steal your credentials. They simply ride on the trust your browser has already established with a legitimate site.
CSRF attacks can be used to change email addresses, reset passwords, make purchases, submit forms, delete accounts — essentially any action a logged-in user can perform.
So What Is a CSRF Token?
A CSRF token (sometimes called an anti-CSRF token or synchroniser token) is a unique, secret, unpredictable value that a server generates and associates with a user’s session. It’s then embedded in any web form or request that could perform a sensitive action.
When that form is submitted, the server checks whether the token in the request matches the one it generated for that session. If the values match, the request is considered legitimate. If they don’t — or if the token is missing altogether — the server rejects the request.
The key insight here is that a CSRF token is something the attacker cannot know. Unlike a session cookie (which the browser sends automatically), a CSRF token has to be explicitly included in the request by the legitimate web page. A malicious third-party site has no way to read the token from your page due to the browser’s same-origin policy, which prevents scripts on one domain from reading content from another.
How Do CSRF Tokens Work in Practice?
Here’s a typical flow:
- User loads a page. When your server renders a form — say, a profile update page — it generates a random CSRF token, stores it in the user’s session on the server side, and embeds it as a hidden field in the HTML form.
html
<form method="POST" action="/update-profile"> <input type="hidden" name="csrf_token" value="a3f8e2c91b774d0e..."> <input type="text" name="email"> <button type="submit">Save Changes</button></form>
- User submits the form. The browser sends the form data along with the hidden CSRF token.
- Server validates the token. The server compares the submitted token against the one stored in the session. If they match, it processes the request. If not, it returns an error — typically a 403 Forbidden.
- Attack fails. An attacker trying to forge this request from their own site cannot read the CSRF token from your page (thanks to same-origin restrictions), so any forged request they craft will be missing or contain an incorrect token.
What Makes a Good CSRF Token?
Not all tokens are created equal. A good CSRF token should be:
- Unpredictable — It must be generated using a cryptographically secure random number generator. A sequential number or timestamp would be far too easy to guess.
- Unique per session (at minimum) — The token should be tied to the user’s current session. Some implementations go further and generate a fresh token per request for even tighter security.
- Sufficiently long — A token of at least 128 bits (rendered as a hex or base64 string) is generally recommended to make brute-force guessing impractical.
- Validated server-side — The comparison must happen on the server, not in client-side JavaScript, and it should use a constant-time comparison to avoid timing attacks.
CSRF Tokens and Modern Web Apps
In traditional server-rendered applications, embedding a CSRF token in an HTML form is straightforward. But modern single-page applications (SPAs) that communicate via APIs require a slightly different approach.
A common pattern for SPAs is the Double Submit Cookie method, where the CSRF token is sent both as a cookie and as a custom request header (such as X-CSRF-Token). Because cross-origin requests cannot set or read custom headers without explicit CORS permissions, this provides a similar layer of protection.
Many popular frameworks handle CSRF protection automatically. Django, Laravel, Rails, Spring Security, and ASP.NET Core all include built-in CSRF middleware that manages token generation and validation behind the scenes — so in many cases, you get this protection without having to think about it, as long as you don’t inadvertently disable it.
Are CSRF Tokens the Only Defence?
CSRF tokens are the most widely used defence, but they’re not the only tool available. The SameSite cookie attribute is a newer, complementary protection: setting cookies to SameSite=Strict or SameSite=Lax instructs browsers not to send them on cross-site requests. This significantly reduces CSRF risk and is now well-supported across modern browsers.
However, relying on SameSite alone isn’t considered sufficient for high-security applications, since browser support and configuration can vary. Using CSRF tokens alongside SameSite cookies gives you defence in depth.
Summary
CSRF tokens are a straightforward but powerful mechanism for ensuring that sensitive actions in your application are genuinely initiated by your users — not quietly forged by a malicious third party. By embedding a secret, session-tied value into every state-changing request and validating it on the server, you close off one of the web’s most persistent classes of attack.
If you’re building a web application, check that your framework’s CSRF protection is enabled and properly configured. It’s one of the easiest security wins available to you.
If you would like help implementing or validating your CSRF token configuration, MIC Solutions Ltd is here to help.
