I'm implementing a custom authentication provider in my app. In my provider, I throw different exceptions with different messages depending on the situation. Please see my code:
@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);
}
}
To catch those exceptions, I implemented a CustomAuthenticationEntryPoint
, like this:
@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);
}
}
As you can see, I resolve the exception so that I can catch it again in my @RestControllerAdvice
(I want to centralize the exception handling).
My problem is that the commence
method of the CustomAuthenticationEntryPoint
turns all exceptions into AuthenticationException
. No matter what exception I throw in my authentication provider, what I get is always an authentication exception with a fixed message:
Full authentication is required to access this resource
In conclusion, I can catch exceptions thrown from the AuthenticationProvider
, but not the correct one.
My question: How can I catch the correct exceptions thrown from the AuthenticationProvider
?