How to Manually Validate a CSRF Token in a Controller
Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.2 (the current stable version).
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:
1 2 3 4 5 6
public function deleteAction()
{
if ($this->isCsrfTokenValid('token_id', $submittedToken)) {
// ... do something, like deleting an object
}
}
2.6
The isCsrfTokenValid()
shortcut method was introduced in Symfony 2.6.
It is equivalent to executing the following code:
1 2 3 4
use Symfony\Component\Security\Csrf\CsrfToken;
$this->get('security.csrf.token_manager')
->isTokenValid(new CsrfToken('token_id', 'TOKEN'));