spring - 将 OAuth2RestTemplate 公开为 AsyncRestTemplate

标签 spring oauth spring-security resttemplate

我有一个正在运行的 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/

相关文章:

spring - 正确使用子类化 spring ContextLoader 进行测试

java - Spring OAuth2 - 在 token 存储中手动创建访问 token

java - 数据库连接超时

java - @cacheable spring for redis,方法特定的ttl?

java - Spring RMI服务器和纯java RMI客户端

java - 为什么这个 spring oauth 配置永远不会返回 401 未经授权?

java - Mockito 不使用 @PreAuthorize 和 Spring Boot 进行模拟

Facebook 服务器端身份验证 : Why does the access token request require a redirect uri?

google-app-engine - 获取用于访问 Google 域下用户数据的持久性 token

testing - Spring security authentication 如何去掉