我有一个有效的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?
答案 0 :(得分:3)
好的,我能够通过手动设置"授权"使AsyncRestTemplate工作。来自OAuth2RestTemplate的accessToken标头;这里是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。
答案 1 :(得分:2)
上述工作,但我发现了一种更简洁的方法。
注册实施 private void getIntentData() {
Bundle bundle = getIntent().getExtras();
if (bundle != null)
Strin url = bundle.getString(key);
}
示例代码:
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