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 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

In Practice

Related concepts

FormsSecurityTwigDebugging