Symfony中如何在AppAuthenticator中修改登录错误消息提示用户未激活
解决方案
你不需要手动修改lastAuthenticationError,Guard认证流程会自动捕获认证过程中抛出的AuthenticationException子类,写入错误存储供AuthenticationUtils读取,只要拆分checkCredentials的校验逻辑,对不同错误场景做不同处理即可。
修改AppAuthenticator的checkCredentials方法:
use Symfony\Component\Security\Core\Exception\DisabledException; class AppAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface { public function checkCredentials($credentials, UserInterface $user) { $passwordOk = $this->passwordEncoder->isPasswordValid($user, $credentials['password']); // 密码校验失败直接返回false,触发默认的「无效凭证」错误 if (!$passwordOk) { return false; } // 密码校验通过后检查用户启用状态 if (!$user->getEnabled()) { // 抛出用户禁用异常,自定义错误消息 throw new DisabledException('该用户未激活'); } return true; } }
后续说明
SecurityController不需要做任何修改,$authenticationUtils->getLastAuthenticationError()会自动获取到你抛出的DisabledException对象,模板中直接输出error.message就能得到「该用户未激活」的提示,和密码错误的提示完全区分,不会出现混淆。
内容的提问来源于stack exchange,提问作者K. Weber
相关产品推荐
相关产品推荐

