【发布时间】:2019-12-28 16:43:38
【问题描述】:
我正在我的应用中实现自定义身份验证提供程序。在我的提供程序中,我会根据情况使用不同的消息抛出不同的异常。请看我的代码:
@Component
public class MyLdapAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Connect to LDAP - throw ConnectionException if the LDAP server is unreachable
// Authenticate
// Worng username or password, throw BadCredentialsException("Incorrect username or password.")
// Not enough right to use my app, throw BadCredentialsException("This user is not allowed to use the service.");
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
为了捕捉这些异常,我实现了一个CustomAuthenticationEntryPoint,如下所示:
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final HandlerExceptionResolver resolver;
@Autowired
public CustomAuthenticationEntryPoint(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
this.resolver = resolver;
}
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, e);
}
}
如您所见,我解决了异常,以便可以在@RestControllerAdvice 中再次捕获它(我想集中处理异常)。
我的问题是CustomAuthenticationEntryPoint 的commence 方法将所有异常转换为AuthenticationException。无论我在身份验证提供程序中抛出什么异常,我得到的始终是带有固定消息的身份验证异常:
访问此资源需要完全身份验证
总之,我可以捕获从AuthenticationProvider 抛出的异常,但不是正确的。
我的问题:如何捕获AuthenticationProvider 抛出的正确异常?
【问题讨论】:
-
不,我的问题是:我怎样才能捕获从
AuthenticationProvider抛出的正确异常?如您所见,我无法捕捉到ConnectionException或BadCredentialsException。 -
我已经检查过了。他们只想抓住
AuthenticationException。对我来说,情况不同。我想捕获特定异常以了解身份验证失败的原因(无法连接到身份验证源、错误的凭据……)。AuthenticationException中没有此信息。 -
在您最后的评论中,您写道您的问题不是关于异常的类型,而是关于捕获异常。因此,我删除了我的最后一条评论。现在又是关于异常的类型。如果您阅读我的最后一条评论,您就会知道您的问题的答案。
-
您的问题:不,我的问题是:我怎样才能捕获从 AuthenticationProvider 抛出的正确异常?在其他问题中得到解答。
-
如您所见,我无法捕获 ConnectionException 或 BadCredentialsException。我的评论中回答了这个问题。
标签: java spring-boot exception spring-security