Handle Security exceptions in Spring Boot Resource Server

后端 未结 8 660
执念已碎
执念已碎 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:47

    We can use this security handler to pass the handler to spring mvc @ControllerAdvice

    @Component
    public class AuthExceptionHandler implements AuthenticationEntryPoint, AccessDeniedHandler {
    
        private static final Logger LOG = LoggerFactory.getLogger(AuthExceptionHandler.class);
    
        private final HandlerExceptionResolver resolver;
    
        @Autowired
        public AuthExceptionHandler(@Qualifier("handlerExceptionResolver") final HandlerExceptionResolver resolver) {
            this.resolver = resolver;
        }
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            LOG.error("Responding with unauthorized error. Message - {}", authException.getMessage());
            resolver.resolveException(request, response, null, authException);
        }
    
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
            LOG.error("Responding with access denied error. Message - {}", accessDeniedException.getMessage());
            resolver.resolveException(request, response, null, accessDeniedException);
        }
    }
    

    Then define the exception by using @ControllerAdvice so that we can manage the global exception handler in one place..

提交回复
热议问题