getLastUsername from AuthenticationUtils always empty

送分小仙女□ 提交于 2021-01-28 10:41:03

问题


So my code is pretty straightforward, I have a login form, an authenticator, and a login method in the controller.

In my authenticator class, when user credentials are wrong, I store the email used in the session. See below ( specifically the getCredentials method ) :

<?php

namespace AppBundle\Security;

use Psr\Log\LoggerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use AppBundle\Form\LoginFormType;


class LoginFormAuthenticator extends AbstractGuardAuthenticator
{

private $passwordEncoder;

private $logger;

private $router;

private $formFactory;

public function __construct(FormFactoryInterface $formFactory, LoggerInterface $logger,UserPasswordEncoderInterface $passwordEncoder, RouterInterface $router)
{
    $this->formFactory = $formFactory;
    $this->router = $router;
    $this->logger = $logger;
    $this->passwordEncoder = $passwordEncoder;
}

public function supports(Request $request)
{
    return ($request->getPathInfo() == '/login' && $request->isMethod('POST'));
}


public function getCredentials(Request $request)
{   
    $form = $this->formFactory->create(LoginFormType::class);

    $form->handleRequest($request);

    $data = $form->getData();

    **$request->getSession()->set(
        Security::LAST_USERNAME,
        $data['email']
    );**

    $test = $request->getSession()->get(Security::LAST_USERNAME);
    $this->logger->info('email : '.$test);

    return $data;
}


public function getUser($credentials, UserProviderInterface $userProvider)
{
    $email = $credentials['email'];
    $this->logger->info('email getUser : '.$email);

    if (null === $email) {
        return;
    }

    return $userProvider->loadUserByUsername($email);
}

public function checkCredentials($credentials, UserInterface $user)
{   

    $plainPassword = $credentials['password'];
    $encoder = $this->passwordEncoder;

    if(!$encoder->isPasswordValid($user, $plainPassword)) {
        return new Response('Password Invalid');
    }

    // return true to cause authentication success
    return true;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    // on success, let the request continue
    return new Response("<html><head></head><body>SUCCESS</body></html>");
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);

    $request->getSession()->set(Security::LAST_USERNAME, $request->get('email'));

    $response = new RedirectResponse($this->router->generate('security_login'));
}

/**
 * Called when authentication is needed, but it's not sent
 */
public function start(Request $request, AuthenticationException $authException = null)
{

    return new Response('Authentication Required');
}

public function supportsRememberMe()
{
    return false;
}


}

So far so good, the email is stored in the session. ( See the getCredentials method ).

However, the same value stored in the session is empty when accessed from the login controller below :

 /**
 * @Route("/login", name="security_login")
 */
public function loginAction(Request $request, AuthenticationUtils $authUtils)
{

    $error = $authUtils->getLastAuthenticationError();

    $last_username = $authUtils->getLastUsername();

    $logger->info('email in SESSION : '.$last_username);


    $form = $this->createForm(LoginFormType::class,[
        'email' => $last_username
    ]);


    return $this->render('security/login.html.twig', [
        'loginForm' => $form->createView(),
        'error'=> $error

    ]);
}

It's just empty, so I'm not sure what's happening here or what I'm doing wrong.

Please advise.

Thanks!

来源:https://stackoverflow.com/questions/48224723/getlastusername-from-authenticationutils-always-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!