5

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 ?

3 Answers 3

10

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your solution. The last line should read = instead of == (but I cannot edit this because edit should be at least 6 characters :'()
As of 2.4 you'll need to use 'security.csrf.token_manager' instead. For the intention/intent you'll probably need "form" or "authenticate". You can see what the intention is in the session data, which should be under var/sessions and have a name equal to that of your PHPSESSION cookie value.
6

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

Comments

1

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.

1 Comment

Thank you for your answer. _token is not there, my_form[_token] is there. I'm using the automatic token handling successfully already, but I need to get this token explicitly for an issue of asynchronous document upload (to be able to gather it back at post time)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.