Я решил эту проблему, реализовав AuthenticationFailureHandler, который вызывается методом unsuccessfulAuthentication, который был реализован в AbstractAuthenticationProcessingFilter ... Это код конфигурации:
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.and()
.authenticationProvider(provider)
.addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
.authorizeRequests()
.requestMatchers(PROTECTED_URLS)
.authenticated()
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable()
;
}
@Bean
TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(successHandler());
filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
return filter;
}
Это AuthenticationFailureHandler:
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception)
throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json");
Map<String, Object> error = new HashMap<>();
error.put("domain", "global");
error.put("reason", "required");
error.put("message", "Invalid credentials.");
ArrayList<Map<String, Object>> errorsList = new ArrayList<>();
errorsList.add(error);
Map<String, Object> errors = new HashMap<>();
errors.put("errors", errorsList);
errors.put("code", 401);
errors.put("message", "Invalid credentials.");
Map<String, Object> data = new HashMap<>();
data.put(
"error", errors);
response.getOutputStream()
.println(objectMapper.writeValueAsString(data));
}
}
В потоке аутентификации, когда я генерирую исключение CredentialsExpiredException, BadCredentialsException или любое исключение аутентификации, вызовет метод unsuccessfulAuthentication из AbstractAuthenticationProcessingFilter и будет выполнять заданный AuthenticationFailureHandler:
public final class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final String BEARER = "Bearer";
public TokenAuthenticationFilter(final RequestMatcher requiresAuth) {
super(requiresAuth);
}
@Override
public Authentication attemptAuthentication(
final HttpServletRequest request,
final HttpServletResponse response) {
final String param = ofNullable(request.getHeader(AUTHORIZATION))
.orElse(request.getParameter("t"));
final String token = ofNullable(param)
.map(value -> removeStart(value, BEARER))
.map(String::trim)
.orElseThrow(() -> new BadCredentialsException("Missing Authentication Token"));
final Authentication auth = new UsernamePasswordAuthenticationToken(null, token);
return getAuthenticationManager().authenticate(auth);
}
@Override
protected void successfulAuthentication(
final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain chain,
final Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException failed)
throws IOException, ServletException {
getFailureHandler().onAuthenticationFailure(request, response, failed);
}
}