Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 2.7 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Manually Validate a CSRF Token in a Controller

2.7 version
Maintained Unmaintained

How to Manually Validate a CSRF Token in a Controller

Sometimes, you want to use CSRF protection in an action where you do not want to use the Symfony Form component. If, for example, you are implementing a DELETE action, you can use the isCsrfTokenValid() method to check the validity of a CSRF token:

public function deleteAction()
    if ($this->isCsrfTokenValid('token_id', $submittedToken)) {
        // ... do something, like deleting an object

New in version 2.6: The isCsrfTokenValid() shortcut method was introduced in Symfony 2.6. It is equivalent to executing the following code:

use Symfony\Component\Security\Csrf\CsrfToken;

    ->isTokenValid(new CsrfToken('token_id', 'TOKEN'));

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.