2017-08-28 34 views
1

我已經配置了一個OAuth2RestTemplate與自定義錯誤處理程序,我想要禁用拋出異常如果狀態是4xx或5xx(我想檢查ResponseEntity本身上的HttpStatus)的默認行爲OAuth2RestTemplate自定義ErrorHandler

實現看起來像這樣

@Bean 
public OAuth2RestTemplate restTemplate(OAuth2ProtectedResourceDetails resourceDetails) { 
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails); 
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { 
     @Override 
     public void handleError(ClientHttpResponse response) throws IOException { 
      // nothing to do 
     } 
    }); 
    return restTemplate; 
} 

當一個請求會導致狀態409(衝突)我總是得到以下異常:

org.springframework.web.client.ResourceAccessException: 上的I/O錯誤「http://localhost:10010/ ...」的POST請求:流已關閉; 嵌套異常是java.io.IOException:流關閉

有沒有什麼辦法可以避免這種異常?如果我刪除自定義錯誤處理程序將有HttpClientErrorException

org.springframework.web.client.HttpClientErrorException:對於任何迴應:)

最好的問候409衝突

謝謝,

伯恩哈德

回答

1

我已經能夠得到異常各地通過創建一個被拋出自定義的OAuth2ErrorHandler的子類,並使用它來代替自定義的ResponseErrorHandler。 OAuth2RestTemplate顯式檢查錯誤處理程序是否爲instanceof OAuth2ErrorHandler。

你應該只需要重寫hasError方法:

public class NoOpResponseErrorHandler extends OAuth2ErrorHandler { 
    NoOpResponseErrorHandler(OAuth2ProtectedResourceDetails resource) { 
     super(resource); 
    } 
    @Override 
    public boolean hasError(ClientHttpResponse response) throws IOException { 
     return response.getStatusCode().equals(HttpStatus.UNAUTHORIZED) || 
       response.getStatusCode().equals(HttpStatus.FORBIDDEN); 
    } 
} 

要與OAuth2RestTemplate使用它,你需要在你的OAuth2ProtectedResourceDetails對象(即ClientCredentialsResourceDetails)通過。

OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails); 
restTemplate.setErrorHandler(new NoOpOAuthErrorHandler(resourceDetails)); 

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/client/OAuth2RestTemplate.java#L91