Symfony 5 keeps redirecting from the register route

I am trying to build a login page register user its working after I wanted to login them in so I used the make: Auth seemed but now Symfony 5 keeps redirecting from the register route to login without saving the users in the DB first when the form is submitted it was working before i ran the make auth cmd

most of the code regaring the user auth

this is the guide i used

on the Symfony docs
i guess that’s why it messing up

When you submit the form, the LoginFormAuthenticator will intercept
the request, read the email (or whatever field you’re using) &
password from the form, find the User object, validate the CSRF token
and check the password

            algorithm: auto 
                class: AppEntityUser
                property: Username
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
            access_denied_handler: AppSecurityAccessDeniedHandler
            anonymous: false
            lazy: true
            provider: users
                login_path: app_login
                check_path: app_login
                    - AppSecurityAuthAuthenticator
                path: app_logout
                # where to redirect after logout
                # target: app_any_route

            # activate different ways to authenticate

            # 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
        # - { path: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }


namespace AppController;

use AppEntityUser;
use AppFormRegistrationFormType;
use AppSecurityEmailVerifier;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentMimeAddress;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use SymfonyCastsBundleVerifyEmailExceptionVerifyEmailExceptionInterface;

class RegistrationController extends AbstractController
    private $emailVerifier;

    public function __construct(EmailVerifier $emailVerifier)
        $this->emailVerifier = $emailVerifier;

     * @Route("/register", name="app_register")
    public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
        $user = new User();
        $form = $this->createForm(RegistrationFormType::class, $user);

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password

            $entityManager = $this->getDoctrine()->getManager();

            // generate a signed url and email it to the user
            $this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
                (new TemplatedEmail())
                    ->from(new Address('[email protected]', 'root'))
                    ->subject('Please Confirm your Email')
            // do anything else you need here, like send an email

            return $this->redirectToRoute('index');

        return $this->render('registration/register.html.twig', [
            'registrationForm' => $form->createView(),

     * @Route("/verify/email", name="app_verify_email")
    public function verifyUserEmail(Request $request): Response

        // validate email confirmation link, sets User::isVerified=true and persists
        try {
            $this->emailVerifier->handleEmailConfirmation($request, $this->getUser());
        } catch (VerifyEmailExceptionInterface $exception) {
            $this->addFlash('verify_email_error', $exception->getReason());

            return $this->redirectToRoute('app_register');

        // @TODO Change the redirect on success and handle or remove the flash message in your templates
        $this->addFlash('success', 'Your email address has been verified.');

        return $this->redirectToRoute('app_register');

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;

class SecurityController extends AbstractController
     * @Route("/login", name="app_login")
    public function login(AuthenticationUtils $authenticationUtils): Response
        if ($this->getUser()) {
            return $this->redirectToRoute('index');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);

     * @Route("/logout", name="app_logout")
    public function logout()
        throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');

{% extends 'base.html.twig' %}
{% block title %}Register{% endblock %}

{% block body %}
    {% for flashError in app.flashes('verify_email_error') %}
        <div class="alert alert-danger" role="alert">{{ flashError }}</div>
    {% endfor %}


    {{ form_start(registrationForm) }}
        {{ form_row(registrationForm.Username) }}
        {{ form_row(registrationForm.plainPassword, {
            label: 'Password'
        }) }}
        {{ form_row(registrationForm.agreeTerms) }}

        <button type="submit" class="btn">Register</button>
    {{ form_end(registrationForm) }}
{% endblock %}


namespace AppSecurity;

use AppEntityUser;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
use SymfonyComponentSecurityCoreExceptionInvalidCsrfTokenException;
use SymfonyComponentSecurityCoreSecurity;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCsrfCsrfToken;
use SymfonyComponentSecurityCsrfCsrfTokenManagerInterface;
use SymfonyComponentSecurityGuardAuthenticatorAbstractFormLoginAuthenticator;
use SymfonyComponentSecurityGuardPasswordAuthenticatedInterface;
use SymfonyComponentSecurityHttpUtilTargetPathTrait;

class AuthAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
    use TargetPathTrait;

    public const LOGIN_ROUTE = 'app_login';

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;

    public function supports(Request $request)
        return self::LOGIN_ROUTE === $request->attributes->get('_route')
            && $request->isMethod('POST');

    public function getCredentials(Request $request)
        $credentials = [
            'Username' => $request->request->get('Username'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),

        return $credentials;

    public function getUser($credentials, UserProviderInterface $userProvider)
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['Username' => $credentials['Username']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException(' Username could not be found.');

        return $user;

    public function checkCredentials($credentials, UserInterface $user)
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);

     * Used to upgrade (rehash) the user's password automatically over time.
    public function getPassword($credentials): ?string
        return $credentials['password'];

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);

        // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
        throw new Exception('TODO: provide a valid redirect inside '.__FILE__);

    protected function getLoginUrl()
        return $this->urlGenerator->generate(self::LOGIN_ROUTE);

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

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