Search code examples
symfonycsrfsymfony-forms

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 ?


Solution

  • 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);