"The CSRF token is invalid. Please try to resubmit the form." A few users report it, nobody can reproduce it locally, and the ticket drags on. Then a fix lands, in one line:
public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'csrf_protection' => false, // "it was blocking people" ]); } I saw it on a client project, and it is not a one-off: in my audits I regularly find forms or routes taken out of the check "because it was blocking people". The error goes away, the ticket gets closed, and the application has just lost a protection without anyone knowing why it was failing.
This article explains what that line really exposes, how to find the real cause with three questions, and how to fix each one. Three of the causes can be reproduced in the Symfony playground, in one click, with nothing to install. If you first want a refresher on what the token protects and how other frameworks handle it, I wrote an article on the CSRF token in Symfony, Laravel, Django and Rails.
What the line really turns off
The usual argument for turning it off: "cookies are SameSite=Lax now anyway". True, Symfony sets SameSite=Lax on its session cookie by default, and it is good protection. It still has holes that the token plugs:
-
SameSitethinks in sites, not origins. To the browser,blog.example.comandapp.example.combelong to the same site. An XSS flaw on another subdomain, or a forgotten subdomain an attacker takes over, and their requests to the application leave with the cookie. - Actions over
GETare not covered.Laxlets the cookie through on a top-levelGETnavigation, a plain link. A route that deletes or approves something overGETis exposed, and adding a token would only leak it into the history and theRefererheader: never change data overGET. - Not every cookie is
Lax. A "remember me" cookie, a cookie set by another component, or a cookie set toSameSite=Nonefor an integration does not benefit from the protection. And for cookies that specify nothing, Chrome still lets a top-levelPOSTthrough for two minutes after they are set. - The login form counts too. Without a token, another site can log the victim into the attacker's account, and
SameSitemakes no difference: that request needs no existing cookie. Everything the victim then types, an address, a card, a document, ends up in the attacker's hands.
SameSite is a second line of defence. Disabling the token means keeping the second line and removing the first, to hide a bug nobody understood.
Finding the cause with three questions
The message is the same whatever the cause: the Form component does not say why it refuses. The profiler of the failing POST request, locally or in staging, answers three questions.
- Did the token arrive? Request tab, POST parameters: look for
form[_token](or_tokenfor a hand-written form). If it is missing, the problem is in the template or in the JavaScript that sends the form. - For a classic token, is it the same session? Compare the session cookie (
PHPSESSIDby default) between displaying the form and submitting it, and check whether the session of thePOSTrequest still holds its tokens (_csrf/…attributes). A missing or different cookie, an empty session: the token has nothing left to be compared with. - Is the token stateless? Since Symfony 7.2, the
symfony/formrecipe creates aconfig/packages/csrf.yamlfile that makes the tokens of forms (idsubmit), login and logout stateless. The 8.2 recipes split it intoform.yamlandcsrf_protection.yaml, and an older project only gets these files after acomposer recipes:update: without them, its tokens stay in the session. Stateless tokens are not stored in the session: Symfony checks theOriginorRefererheaders. In that case, question 2 does not apply. The Logs tab then gives the exact reason, for exampleCSRF validation failed: origin info doesn't match.
With these three answers, the cause is in the list below.
The causes, and their fix
The _token field is never sent
A template that renders fields one by one, to control the layout, then closes the tag by hand:
{{ form_start(form) }} {{ form_errors(form) }} {{ form_row(form.title) }} {{ form_row(form.publish) }} </form> Nobody renders the hidden _token field: every submit is refused, for everyone. Fix : close with {{ form_end(form) }}, which renders the remaining fields, token included. If you really must write the tag by hand, at least render {{ form_rest(form) }} before it.
Same family: a form sent in JavaScript, with fetch(), that builds its body field by field and forgets the token. Send the whole form with new FormData(form), and the token follows.
▶ Reproduce the forgotten field in the Symfony playground
The session expired, or does not follow
For a classic token, stored in the session (a project older than Symfony 7.2, or an id not in stateless_token_ids), this is the most frequent cause, and the only one that is not a bug. The user opens the form, goes to lunch, comes back, submits. Meanwhile, PHP has deleted the session, whose lifetime had run out, and the token received has nothing left to be compared with. The variants, on the other hand, are configuration bugs:
- the session cookie does not arrive : wrong cookie domain,
Securecookie on a page served overhttp, cookie blocked by the browser; - several servers do not share their sessions : the page comes from server A, the submit reaches server B, which does not know that session. Store sessions in shared storage (database, Redis);
- the page is served from a cache : a CDN or reverse proxy set to cache everything, ignoring the
Cache-Control: privatethat Symfony sets as soon as a session is used, hands the same page, so the same token, to every visitor. Stateless tokens do not have this problem: the same page can be cached.
For the expiry itself, there is nothing to "fix", but a lot to polish. The Form component keeps what was typed and renders the form with a fresh token: a second submit goes through. Replace the technical message with a sentence the user understands, along the lines of "Your session expired while you were typing. Your text is kept: check it and submit the form again." And if your users fill in long forms, extend the session lifetime (framework.session.gc_maxlifetime, and cookie_lifetime if the cookie expires first) rather than removing the token.
▶ Reproduce the expired session in the Symfony playground
The token id differs
For a hand-written form, the token is built in Twig and checked in the controller, each with an id:
<input type="hidden" name="_token" value="{{ csrf_token('delete-article-' ~ article.id) }}"> if (!$this->isCsrfTokenValid('delete_article_'.$id, $request->request->getString('_token'))) { // refused every time } Hyphens on one side, underscores on the other: they are not the same tokens, and the check fails on every submit, even on a brand new session. The typical case is a rename done on one side only. Fix : the same id on both sides. The #[IsCsrfTokenValid(new Expression('"delete-article-" ~ args["id"]'))] attribute on the controller does not guarantee that both ids match, but it puts the controller's id in plain sight, right above the method.
▶ Reproduce the different id in the Symfony playground
The stateless token does not recognise the origin
With a stateless token, Symfony compares the Origin header (or, failing that, Referer) sent by the browser with the address it thinks it serves. Behind a reverse proxy, a load balancer or anything else that terminates HTTPS, the application receives the request over http: it thinks it is on http://example.com, the browser announces https://example.com, and every submit is refused. The logs say CSRF validation failed: origin info doesn't match.
Fix : declare the proxy, so that Symfony reads the X-Forwarded-* headers it sends.
# config/packages/framework.yaml framework: trusted_proxies: '%env(TRUSTED_PROXIES)%' # for example 127.0.0.1,REMOTE_ADDR behind a single proxy The X-Forwarded-For, -Proto and -Port headers are read by default as soon as trusted_proxies is set. Add x-forwarded-host to trusted_headers if the proxy also rewrites the host.
This setting is not only for the token: without it, the absolute URLs Symfony generates also go out over http, and every IP address in the logs is the proxy's.
The other possible reason is CSRF validation failed: double-submit and origin info not found.: the request had neither Origin nor Referer, for example because a browser extension or a corporate proxy strips them. Symfony then falls back on a cookie set by the Stimulus controller csrf_protection_controller.js, which the symfony/stimulus-bundle recipe installs in assets/controllers/. If that JavaScript is not loaded on the page, the fallback does not work: check that the controller is registered, or give this form a classic, session-stored token again, with the 'csrf_token_id' => 'my_form' option in configureOptions() (an id that is not in stateless_token_ids). The fallback cookie's name also depends on the protocol (__Host- prefix over HTTPS): behind an undeclared proxy, it fails too.
When going without the token is legitimate
There are cases where the csrf_protection: false option is the right answer, and they all have one thing in common: the request is not authenticated by a cookie the browser attaches on its own.
- An API authenticated by a header
Authorization: Bearer …. Another site cannot make the victim's browser add that header. A Symfony form used to validate that API's JSON can do without a token. - A webhook (Stripe, GitHub…). It has no session, and it has its own proof: a signature, to check every time.
On the other hand, an API called by your own pages in JavaScript, with the session cookie, remains exposed: it needs the token, sent in a header that the controller checks.
What I take away
The CSRF error is a symptom, almost always of something else: a template, a session, a proxy. Disabling it hides the symptom and removes a protection, without fixing anything. The profiler's three questions take five minutes and give the cause in most cases.
To practise, the CSRF concept gathers the exercises that handle the token, from the form generated by the Form component to the hand-written form, with a token of its own for each deleted item.
