How to use symfony csrf token validation?

I am using this twig and standalone symfony form and validator component:

use Symfony\Component\Validator\Constraints as Assert;
// other use lines ommitted to shorten the code.

$defaultFormTheme = 'bootstrap_4_horizontal_layout.html.twig';

$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new NativeSessionTokenStorage();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formEngine = new TwigRendererEngine([$defaultFormTheme], $twig);
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
    FormRenderer::class => function () use ($formEngine, $csrfManager) {
        return new FormRenderer($formEngine, $csrfManager);
    },
]));
$twig->addExtension(new FormExtension());

$translator = new Translator('fr_FR');
$translator->addLoader('php', new \Symfony\Component\Translation\Loader\PhpFileLoader());
$translator->addResource('php', ROOT.'/translations/messages.fr.php', 'fr_FR');
$twig->addExtension(new TranslationExtension($translator));

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new CsrfExtension($csrfManager))
    ->addExtension(new ValidatorExtension(Validation::createValidator()))
    ->getFormFactory();

$form = $formFactory->createBuilder()
    ->add('firstnameEn', TextType::class, [
            'constraints' => [new Assert\Length(['min' => 3])]
        ])
    ->add('lastnameEn', TextType::class)
    ->add('email', EmailType::class)
    ->add('birthDate', TextType::class)
    ->add('password', PasswordType::class)
    ->add('applyCard', CheckboxType::class)
    ->add('showPhoto', CheckboxType::class)
    ->add('privacyRead', CheckboxType::class)
    ->getForm();

$form->handleRequest();

if ($form->isSubmitted() && $form->isValid()) {

   $errors = $form->getErrors();
   var_dump($errors);
   $data = $form->getErrors();
   var_dump($data);
   print("debug pring");

} else {

   $errors = $form->getErrors();
   var_dump($errors);
   $data = $form->getErrors();
   var_dump($data);
   print("debug pring");

}

echo $twig->render('signup.html', 
['form' => $form->createView(),
 'title' => 'title',
]);

I looked html source and I see there is field like:

<input type="hidden" id="form__token" name="form[_token]" value="YTm....." />

But I always get an invalid csrf token error, after submitting the form even with a fresh form page. What mistake I did? Should I do something else in this code too?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.