Spring 如何在自定义AuthenticationFailureHandler中返回由具体派生的AuthenticationException类型解析的不同错误消息

Spring 如何在自定义AuthenticationFailureHandler中返回由具体派生的AuthenticationException类型解析的不同错误消息,spring,rest,spring-mvc,authentication,spring-security,Spring,Rest,Spring Mvc,Authentication,Spring Security,我正在使用SpringSecurity构建我的博客应用程序的身份验证/授权。我们决定使用RESTful api,为了在服务器端处理身份验证错误时向客户端返回json消息,我必须编写自定义AuthenticationFailureHandler,如: public类RganAuthenticationFailureHandler实现AuthenticationFailureHandler{ 私有静态记录器Logger=LoggerFactory.getLogger(RganAuthenticati

我正在使用SpringSecurity构建我的博客应用程序的身份验证/授权。我们决定使用RESTful api,为了在服务器端处理身份验证错误时向客户端返回json消息,我必须编写自定义
AuthenticationFailureHandler
,如:

public类RganAuthenticationFailureHandler实现AuthenticationFailureHandler{
私有静态记录器Logger=LoggerFactory.getLogger(RganAuthenticationFailureHandler.class);
@凌驾
AuthenticationFailure(HttpServletRequest HttpServletRequest,HttpServletResponse HttpServletResponse,AuthenticationException e)上的公共无效引发IOException,ServletException{
httpServletResponse.setContentType(MediaType.APPLICATION\u JSON\u值);
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().write(“一些描述”);
}
}
AuthenticationException
有一些具体的派生类型,描述确切的错误,如:
UsernameNotFoundException
BadCredentialsException
AuthenticationServiceException

在我看来,对于不同的异常类型,我应该返回不同的错误消息。例如,对于
UsernameNotFoundException
BadCredentialsException
,我可能会返回“错误的用户名或密码,对于
AuthenticationServiceException
,我可能会返回“在获取凭据期间发生了一些错误,请稍后重试”和其他HTTP状态代码(如500)

现在问题来了,我知道我可以编写如下代码:

if(UsernameNotFoundException的e实例| | BadCredentialsException的e实例){
httpServletResponse.getWriter.write(“message1”);
}else if(e AuthenticationServiceException实例){
httpServletResponse.getWriter.write(“message2”);
}否则如果(…){
// ...
}
要处理这个问题,但这似乎不是最好的解决方案,我必须编写一系列的
else if
block

我读过一些帖子,比如,似乎使用@ControllerAdvice和
HandlerExceptionResolver
也不是最好的解决方案


那么我应该如何处理这个问题呢?

您可以使用

委托给其他用户的AuthenticationFailureHandler AuthenticationFailureHandler实例基于 传递到onAuthenticationFailure的AuthenticationException异常


你的意思是像提供
映射到
DelegatingAuthenticationFailureHandler
的构造函数,并将其用作我的应用程序的
failureHandler
?我想你至少可以为此添加一个代码示例。