Symfony 2. CSRF token is invalid

2019-07-24 19:26发布

I have a problem with a token form in Symfony2. (2.7.0)

Action:

public function registerProcessAction(Request $request){
    $form = $this->createForm(new RegistrationType(), new Registration());

    $form->handleRequest($request);

    if ($form->isValid()) {
        die('valid');
    }
    else{
        die('invalid');
    }
}

And my Form:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class'        => 'My\Bundle\Entity\User'
    ));
}

When I test the form, always show the same error: "The CSRF token is invalid. Please try to resubmit the form". I sure of the input hidden it's in the form. This is the view:

<?php
echo $view['form']->start($form);
echo $view['form']->widget($form);
echo $view['form']->end($form);
?>

Anyone can help me?

I tested to disable the csrf protection, like this:

Action:

$form = $this->createForm(new RegistrationType(), new Registration(), array('csrf_protection' => false));

Form:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class'        => 'My\Bundle\Entity\User',
        'csrf_protection'   => false
    ));
}

But a different error appears: This form should not contain extra fields. Because the hidden input of token, it's in the form yet, and I don't know to remove it.

Thankyou!

1条回答
一夜七次
2楼-- · 2019-07-24 19:40

I have a custom authentication provider, as described here. At some point in the Listener's handle() method, I was calling $request->getSession()->migrate(), which was causing the problem for me. Removing the call to migrate the session solved the problem.

I wonder if this was the commit that broke my authentication listener?

查看更多
登录 后发表回答