我有一个正在运行的 OAuth2RestTemplate 客户端(我正在使用 spring-security-oauth2 2.0.7.RELEASE)。现在我想将其公开/包装为 AsyncRestTemplate 以利用 ListenableFuture 的异步语义。不幸的是,以下简单的方法不起作用:
// instantiate and configure OAuth2RestTemplate - works
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(...);
// wrap sync restTemplate with AsyncRestTemplate - doesn't work
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(
new HttpComponentsAsyncClientHttpRequestFactory(), oAuth2RestTemplate);
如何为我的 HTTP 服务获取 OAuth2 Rest 客户端作为 AsyncRestTemplate?
最佳答案
好的,我可以通过使用 OAuth2RestTemplate 中的 accessToken 手动设置“Authorization” header 来使 AsyncRestTemplate 工作;这是 Spring java 配置:
@Bean
public OAuth2RestTemplate restTemplate() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
// configure oauth details
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details);
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
return restTemplate;
}
@Bean
public AsyncRestTemplate asyncRestTemplate(final OAuth2RestTemplate oAuth2RestTemplate) {
HttpComponentsAsyncClientHttpRequestFactory asyncRequestFactory = new HttpComponentsAsyncClientHttpRequestFactory() {
@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
AsyncClientHttpRequest asyncRequest = super.createAsyncRequest(uri, httpMethod);
OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();
asyncRequest.getHeaders().set("Authorization", String.format("%s %s", accessToken.getTokenType(), accessToken.getValue()));
return asyncRequest;
}
};
return new AsyncRestTemplate(asyncRequestFactory, oAuth2RestTemplate);
}
我希望有更简单的方法在 Spring 中将配置的 OAuth2RestTemplate 公开为 AsyncRestTemplate。
关于spring - 将 OAuth2RestTemplate 公开为 AsyncRestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32876559/