"The CSRF token is invalid. Please try to resubmit the form."

I’m actually doing Register/Login management in my project but i have a little problem.

I readed FOSUserBundle is not compatible with Symfony 5 so i started to use MakerBundle for the first time. I followed some tutorial bug every tutorial are using Twig. I do not want to use it.
I’m using Postman to do resquest.

When i do request:

Url: POST https://127.0.0.1:8000/register
Body: { "user": {
    "username": "test",
    "email": "test",
    "password": "test",
    "roles": []
    }   
}
Headers: Content-Type: application/json

I have this error:

{
    "code": 400,
    "message": "Validation Failed",
    "errors": {
        "errors": [
            "The CSRF token is invalid. Please try to resubmit the form."
        ],
        "children": {
            "username": [],
            "email": [],
            "password": [],
            "roles": {
                "children": [
                    []
                ]
            }
        }
     }
 }

RegisterController.php:

<?php

namespace AppController;
use AppEntityUser;
use AppFormUserType;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use FOSRestBundleViewView;

class RegisterController extends AbstractController
{
    private $passwordEncoder;

    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->passwordEncoder = $passwordEncoder;
    }

    /**
     * @Route("/register", name="register")
     * @param Request $request
     * @return View
     */
    public function index(Request $request)
    {
        $user = new User();

        $form = $this->createForm(UserType::class, $user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Encode the new users password
            $user->setPassword($this->passwordEncoder->encodePassword($user, $user->getPassword()));

            // Set their role
            $user->setRoles(['ROLE_USER']);

            // Save
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            return View::create($user, 201);
        }
        return View::create($form, 400);
    }
}

UserType.php:

<?php

namespace AppForm;

use AppEntityUser;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username')
            ->add('email')
            ->add('password')
            ->add('roles')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'csrf_protection' => true,
        ]);
    }
}

security.yaml:

security:
encoders:
    AppEntityUser:
        algorithm: auto

# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    # used to reload user from session & other features (e.g. switch_user)
    app_user_provider:
        entity:
            class: AppEntityUser
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: lazy
        provider: app_user_provider
        guard:
            authenticators:
                - AppSecurityLoginFormAuthenticator
        logout:
            path: app_logout
            # where to redirect after logout
            target: /
        #guard:
        #    authenticators:
        #        - AppSecurityLoginFormAuthenticator
        #logout:
        #    path: app_logout
            # where to redirect after logout
            # target: app_any_route

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#firewalls-authentication

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }

How can i solve this problem ?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *