OAuth2RestOperations使用从请求标头获得的令牌,而不是请求身份验证服务器

问题描述

我有一个使用OAuth2RestTemplate作为OAuth2Client的spring boot客户端应用。我已经配置了OAuth2RestTemplate来调用authserver并将从中获取的令牌添加到标头中以访问资源服务器。 发生的问题是,每当我使用restTemplate调用客户端应用程序中的方法以访问资源服务器时,它都使用来自客户端应用程序请求标头的令牌,而不是调用身份验证服务器。 它使用该令牌,并且该令牌被我的资源服务器拒绝。在被拒绝之后,它只会调用身份验证服务器并放入正确的令牌,然后再次将请求发送到我的资源服务器。

是否有任何方法可以使rest模板在连接资源服务器之前不使用标头中的令牌并为令牌调用auth服务器? 谢谢你

我的配置类

@Configuration
@EnableOAuth2Client
public class OAuth2ClientConfig {

    @Autowired
    ConfigProperties configProperties;

    @Bean("oauth2AuthServer")
    public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(),oauth2ClientContext);
        oAuth2RestTemplate.setAccessTokenProvider(new CustomResourceOwnerPasswordAccessTokenProvider());
        return oAuth2RestTemplate;
    }

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setId(configProperties.getClientId());
        resource.setAccessTokenUri(configProperties.getAccessTokenUri());
        resource.setClientId(configProperties.getClientId());
        resource.setClientSecret(configProperties.getClientSecret());
        resource.setGrantType(configProperties.getGrantType());
        resource.setClientAuthenticationScheme(AuthenticationScheme.header);
        resource.setAuthenticationScheme(AuthenticationScheme.header); // 
        resource.setUsername(configProperties.getUsername());
        resource.setPassword(configProperties.getPassword());
        return resource;
    }

}

我的serviceImpl方法是

@Autowired
    @Qualifier("oauth2AuthServer")
    private OAuth2RestOperations oauth2RestOperations;

RequestResponse callResourceServer(ResourceRequest request) {
        try {
            RequestResponse response;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON); 
            HttpEntity<ReseourceRequest> entity = new HttpEntity<>(request,headers);
            response = this.oauth2RestOperations.postForObject(
                    microServiceConfig.getUrl(),entity,RequestResponse.class
            );
            return response;
        } catch (Exception ex) {
            log.error(ex);
            throw new exception("error");
        }
    }

解决方法

我看到不赞成使用BaseOAuth2ProtectedResourceDetails和Oauth2RestTemplate,我们还能使用它们吗?否则我们应该迁移到5.x选项

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...