问题描述
在Symfony 4中登录我的应用程序时,出现身份验证错误问题。 我可以完美地与所有用户登录,但是当我故意使登录失败时,我没有收到任何错误消息,也没有$ error出现。在这里,我发布了LoginFormAuthenticator和securityController的代码。 LoginFormAuthenticator
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
/**
* @var UserRepository
*/
private $userRepository;
/**
* @var RouterInterface
*/
private $router;
/**
* @var CsrfTokenManagerInterface
*/
private $csrfTokenManager;
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
public function __construct(UserRepository $userRepository,RouterInterface $router,CsrfTokenManagerInterface $csrfTokenManager,UserPasswordEncoderInterface $passwordEncoder)
{
$this->userRepository = $userRepository;
$this->router = $router;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return $request->attributes->get('_route') === 'app_login'
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'cargo' => $request->request->get('cargo'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),];
$request->getSession()->set(
Security::LAST_USERNAME,$credentials['cargo']
);
return $credentials;
}
public function getUser($credentials,UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate',$credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
return $this->userRepository->findOneBy(['cargo' => $credentials['cargo']]);
}
public function checkCredentials($credentials,UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user,$credentials['password']);
}
public function onAuthenticationFailure(Request $request,AuthenticationException $exception)
{
// todo
}
public function onAuthenticationSuccess(Request $request,TokenInterface $token,$providerKey)
{
return new RedirectResponse($this->router->generate('app_homepage'));
}
public function start(Request $request,AuthenticationException $authException = null)
{
// todo
}
public function supportsRememberMe()
{
// todo
}
protected function getLoginUrl()
{
return $this->router->generate('app_login');
}
}
登录功能:
/**
* @Route("/login",name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils)
{
// 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,]);
}
登录HTML树枝
<form class="form-signin" method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData,'security') }}</div>
<h3>{{ error.messageKey }}</h3>
{% endif %}
谢谢!
解决方法
onAuthenticationFailure方法为空。参见parent :: onAuthenticationFailure。 方法应返回Response对象。