Handle Security exceptions in Spring Boot Resource Server

后端 未结 8 658
执念已碎
执念已碎 2021-01-31 05:36

How can I get my custom ResponseEntityExceptionHandler or OAuth2ExceptionRenderer to handle Exceptions raised by Spring security on a pure resource ser

相关标签:
8条回答
  • 2021-01-31 05:56

    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.

    0 讨论(0)
  • 2021-01-31 06:00

    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.

    0 讨论(0)
提交回复
热议问题