Handle Security exceptions in Spring Boot Resource Server

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

    If you're using token validation URL with config similar to Configuring resource server with RemoteTokenServices in Spring Security Oauth2 which returns HTTP status 401 in case of unauthorized:

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("https://token-validation-url.com");
        tokenService.setTokenName("token");
        return tokenService;
    }
    

    Implementing custom authenticationEntryPoint as described in other answers (https://stackoverflow.com/a/44372313/5962766) won't work because RemoteTokenService use 400 status and throws unhandled exceptions for other statuses like 401:

    public RemoteTokenServices() {
            restTemplate = new RestTemplate();
            ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
                @Override
                // Ignore 400
                public void handleError(ClientHttpResponse response) throws IOException {
                    if (response.getRawStatusCode() != 400) {
                        super.handleError(response);
                    }
                }
            });
    }
    

    So you need to set custom RestTemplate in RemoteTokenServices config which would handle 401 without throwing exception:

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("https://token-validation-url.com");
        tokenService.setTokenName("token");
        RestOperations restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
                @Override
                // Ignore 400 and 401
                public void handleError(ClientHttpResponse response) throws IOException {
                    if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                        super.handleError(response);
                    }
                }
            });
        }
        tokenService.setRestTemplate(restTemplate);
        return tokenService;
    }
    

    And add dependency for HttpComponentsClientHttpRequestFactory:

    
      org.apache.httpcomponents
      httpclient
    
    

提交回复
热议问题