Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46188

CSRF Token from the controller

I have a controller getting a form posted.

public function myPostAction(Request $request)
{
    $form = $this->createForm('my_form', $my_object);
    $form->handleRequest($request);
#...

I can see my CSRF token posted as parameter

my_form[_token] => lH38HTm5P0Cv3TOc4-9xi2COx-cZ670mpJ_36gR8ccI

I simply need to read it

$form->get('_token')

This tells me

Child "_token" does not exist.

How can I get this token ?

Upvotes: 5

Views: 12854

Answers (3)

Like @Pierre de LESPINAY said, it is possible to do it by retrieving Token Manager service.

This service can also be injected in your constructor like that :

use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
...
public function __construct(CsrfTokenManagerInterface $tokenManager)
{
    $this->tokenManager = $tokenManager;
}

And used later like previously demonstrated :

$token = $this->tokenManager->getToken('myformname')->getValue();

Upvotes: 6

Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46188

Here is the workaround I'm going to use meanwhile:

$token = $request->get($form->getName())['_token'];

I also noticed by chance that the intention used to generate the token is the form name

$csrf = $this->get('form.csrf_provider');
$intention = $form->getName();
$token = $csrf->generateCsrfToken($intention);

Upvotes: 10

Michael Sivolobov
Michael Sivolobov

Reputation: 13300

You can get it with:

$request->request->get('my_form[_token]');

If you didn't disable CSRF-protection it will be applied and validated automatically and you don't need to check it by self.

Upvotes: 1

Related Questions