PHP – CSRF Protection with Symfony

  authentication, csrf, forms, php, symfony

I need to create a login form with Symfony and protect it with CSRF protection.
So I use FormBuilder of Symfony.
When the user enter his email and password and submit the form he stay on the same page and the form builder send me that there is an error with CSRF Token.
If I debug the session variable and the token from the form there are different. But when the user reload the page it’s ok those two variables are equals. It’s like my session is overwrite or something like this.
The login page are on one url and the page where it redirect on another url.
Those two domains are on HTTPS.

My session at first attempt

My form variables at first attempt

My session at second attempt

My form variables at second attempt

This is the code of my controller :

    $userForm = new Users();
    $form = $this->createFormBuilder($userForm)
        ->add('email', EmailType::class)
        ->add('password', PasswordType::class)
        ->add('connect', SubmitType::class)


    if($form->isSubmitted() && $form->isValid()) {
        $userForm = $form->getData();

        $user = $this->getDoctrine()->getRepository(Users::class)
            ->findOneBy(array('email' => $userForm->getEmail(), 'is_activated' => 1));

        if ($user != null) {
            if (password_verify($userForm->getPassword(), $user->getPassword())) {
                $id_user = $user->getId();

        if (isset($id_user)) {
            $redirectURL = "my-redirect-url";

        return $this->redirect($redirectURL);
    return $this->render('View/login-debug.html.twig', ['form' => $form->createView()]);

And on my twig view I use the formbuilder : {{form}}.
So I hope it create the token in the right way !

I think I’ve made a little mistake on my script but I don’t know where …

Thank you for your help !

Source: Symfony Questions