Symfony 4 JSON登录:如何返回无效用户名/密码而非通用提示
Symfony 4 JSON登录:区分用户名/密码错误提示
要实现区分“invalid username”和“invalid password”的提示,你需要利用Symfony认证流程中抛出的具体异常类型,修改自定义的失败处理器即可:
修改后的失败处理器代码
<?php namespace App\Security; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; /** * Class LoginFailureHandler * @package App\Security */ class LoginFailureHandler implements AuthenticationFailureHandlerInterface { /** * @param Request $request * @param AuthenticationException $exception * @return Response */ public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { // 取出原始异常(部分场景下AuthenticationException是包装后的上层异常) $originalException = $exception->getPrevious() ?? $exception; // 根据异常类型分配对应提示 if ($originalException instanceof UsernameNotFoundException) { $message = 'invalid username'; } elseif ($originalException instanceof BadCredentialsException) { $message = 'invalid password'; } else { // 其他认证失败场景的默认提示 $message = 'Bad credentials'; } return new JsonResponse([ 'login' => false, 'valid' => false, 'message' => $message ], Response::HTTP_UNAUTHORIZED); } }
关键说明
Symfony的默认认证流程中:
- 当输入的用户名不存在时,
DaoAuthenticationProvider会抛出UsernameNotFoundException - 当用户名存在但密码不匹配时,会抛出
BadCredentialsException - 部分场景下这些异常会被上层认证管理器包装为
AuthenticationException,因此需要通过getPrevious()获取原始异常
如果你自定义了用户提供者(比如实现UserLoaderInterface的仓库类),需要确保找不到用户时抛出UsernameNotFoundException,这是Symfony的标准行为,默认实现已经满足该要求。
内容的提问来源于stack exchange,提问作者noname
相关产品推荐
相关产品推荐

