How can I get my custom ResponseEntityExceptionHandler
or OAuth2ExceptionRenderer
to handle Exceptions raised by Spring security on a pure resource ser
You are not able to make use of Spring MVC Exception handler annotations such as @ControllerAdvice
because spring security filters kicks in much before Spring MVC.
In case if you're using @EnableResourceServer
, you may also find convenient to extend ResourceServerConfigurerAdapter
instead of WebSecurityConfigurerAdapter
in your @Configuration
class. By doing this, you may simply register a custom AuthenticationEntryPoint
by overriding configure(ResourceServerSecurityConfigurer resources)
and using resources.authenticationEntryPoint(customAuthEntryPoint())
inside the method.
Something like this:
@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(customAuthEntryPoint());
}
@Bean
public AuthenticationEntryPoint customAuthEntryPoint(){
return new AuthFailureHandler();
}
}
There's also a nice OAuth2AuthenticationEntryPoint
that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint
. In particular, it adds "WWW-Authenticate" headers with error-related details.