CSRF token: what it is, and the "invalid token" error
A CSRF token is a random value placed in every form: another site cannot read it, and Symfony rejects requests forged elsewhere.
// The template sends the token in a hidden field: // <input type="hidden" name="_token" value="{{ csrf_token('supprimer-plat-' ~ plat.id) }}"> #[Route('/cuisine/plat/{slug:plat}/supprimer', methods: ['POST'])] public function supprimerPlat(Plat $plat, Request $request): Response { if (!$this->isCsrfTokenValid('supprimer-plat-'.$plat->getId(), $request->request->getString('_token'))) { throw new AccessDeniedHttpException('Invalid CSRF token.'); } // … }
A forged request leaves from the victim's browser, with their cookies: without any other clue, the server takes it for a legitimate action. The token makes the difference. The Form component adds and checks it on its own, in a hidden _token field. For a hand-written form, you generate it with csrf_token() in Twig and check it with isCsrfTokenValid() in the controller, as above. The classic traps: a token id that differs between the template and the controller, and every submission is rejected; a deletion triggered by a plain GET link, which no token protects.
"The CSRF token is invalid. Please try to resubmit the form."
This is the Form component's message when the token received doesn't match the expected one. The form is not processed, and the error shows at the top if the template renders the form errors. The same message appears when the field is missing. The most common causes:
- The session expired or was lost. The classic token is stored in the session: a tab left open too long, a logout in another tab, a session cookie that is blocked or set on another domain, and the token sent has nothing left to be compared with. Same thing with several servers that don't share their sessions.
- The page is served from a cache. An HTTP cache or a reverse proxy hands out the same page, so the same token, to everyone: it matches no other visitor's session.
- The
_tokenfield is not rendered. A template that renders the fields one by one withoutform_end()orform_rest()forgets the hidden field. - The stateless token doesn't get through. Since Symfony 7.2, the
symfony/formrecipe enables stateless tokens for forms (projects created, or recipe updated, since then). The check compares theOriginorRefererheaders with the site's address: behind a badly declared reverse proxy (trusted_proxies), the application thinks it's onhttpwhile the browser announceshttps, and every submission is rejected. Without these headers, it falls back on the cookie set by thecsrf_protection_controller.jsStimulus controller: if that JavaScript isn't loaded, the submission is rejected too.
The profiler helps decide: it shows whether the _token field arrived in the request and whether the session existed, and its Logs tab gives the exact reason for the rejection.
To go further, I explain in an article what the CSRF token really protects, when it is still useful now that SameSite cookies exist, and how Symfony, Laravel, Django and Rails handle it.
The exercises go from the form generated by the Form component to a hand-written POST form to take a dish off the menu, with a token specific to each dish, then to a cursed form whose token no longer matches.
5 exercises work on this concept, by writing code in the browser.
In the tracks
- A proper form Symfony for PHP developers · chapter 3: The tavern's scrolls
- Taking a dish off the menu Symfony for PHP developers · chapter 3: The tavern's scrolls
- 🐉 Boss: the cursed scroll Symfony for PHP developers · chapter 3: The tavern's scrolls
In Practice
- Protecting a delete action with a CSRF token A "Remove" link sent as a GET deletes the dish for the first bot that comes along: switch to POST, with a CSRF token for each dish.
- Log out with a button, not with a link logout_button() renders a POST logout form, CSRF token included: a link followed by a bot no longer logs anyone out.