I am trying to use @ControllerAdvice
annotation to return custom JSON responses in spring boot. Below is my code. defaultExceptionHandler
gets called fine if there is an error in the application or spring boot service throws an exception. But handleAuthenticationException
never gets called even if I enter bad credentials. In this case, default spring-boot response is returned. This service is security confi is setup to use basic auth.
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler({AuthenticationException.class})
public ServiceError handleAuthenticationException(final Exception ex) {
//LOGGER.error(ex.toString(), ex);
return new ServiceError(ServiceErrorCode.REQUEST_INVALID, ex.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
@ExceptionHandler(Exception.class)
public ServiceError defaultExceptionHandler(final Exception ex) {
//LOGGER.error(ex.toString(), ex);
return new ServiceError(ServiceErrorCode.SERVICE_ERROR, ex.getMessage());
}
}
Default response which is getting return instead of custom response:
{
"timestamp": 16654436345,
"status": 401,
"error": "Unauthorized",
"message": "Bad credentials",
"path": "/mycontroller"}
Securtiy config class:
@Configuration
public static class ServiceWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.
csrf().
disable().
exceptionHandling().
and().
headers().
frameOptions().
disable().
and().
sessionManagement().
sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().
authorizeRequests().
antMatchers("/service/**").authenticated().
antMatchers("/health").permitAll().
antMatchers("/metrics").permitAll().
antMatchers("/info").hasAuthority(AuthoritiesConstants.ADMIN).
anyRequest().authenticated().and().httpBasic();
}
}