我有一个可以工作的OAuth2RestTemplate客户端(我使用的是spring-security-OAuth22.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);如何为我的OAuth2服务获取HTTP客户端作为AsyncRestTemplate?
发布于 2015-10-03 02:52:10
好的,我可以通过手动设置"Authorization“头和OAuth2RestTemplate中的accessToken来让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。
发布于 2017-07-21 16:55:10
上面的方法是有效的,但我发现了一种更简洁的方法。注册实现AsyncClientHttpRequestInterceptor
示例代码:
private class Oauth2RequestInterceptor implements AsyncClientHttpRequestInterceptor
{
private final OAuth2RestTemplate oAuth2RestTemplate;
public Oauth2RequestInterceptor( OAuth2RestTemplate oAuth2RestTemplate )
{
this.oAuth2RestTemplate = oAuth2RestTemplate;
}
public ListenableFuture<ClientHttpResponse> intercept( HttpRequest request, byte[] body,
AsyncClientHttpRequestExecution execution ) throws IOException
{
OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();
request.getHeaders()
.set( "Authorization", String.format( "%s %s", accessToken.getTokenType(), accessToken.getValue() ) );
return execution.executeAsync( request, body );
}
}然后将其注册到您的AsyncRestTemplate
@Bean
public AsyncRestTemplate asyncRestTemplate( AsyncClientHttpRequestFactory factory, OAuth2RestTemplate restTemplate )
{
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate( factory, restTemplate );
asyncRestTemplate.setInterceptors( Collections.singletonList( new Oauth2RequestInterceptor( restTemplate ) ) );
return asyncRestTemplate;
}https://stackoverflow.com/questions/32876559
复制相似问题