使用OAuth2RestTemplate请求HTTPS资源

时间:2019-01-10 13:23:13

标签: java spring-boot resttemplate spring-oauth2

我正在尝试从使用SSL保护的API中获取一些数据。我已经为OAUth2RestTemplate配置了必要的配置,但是出现了以下异常

Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://.../oauth/token": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

这是我的RestTemplate配置:

@EnableOAuth2Client
@Configuration
public class RestTemplateConfig {

    private final MyConfig config;

    public RestTemplateConfig(MyConfig config) {
        this.config = config;
    }

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {

        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>();
        scopes.add("read");
        resource.setAccessTokenUri(nikolaConfig.getBaseUrl() + "/oauth/token");
        resource.setClientId("...");
        resource.setClientSecret("...");
        resource.setGrantType("...");
        resource.setScope(scopes);

        resource.setUsername(config.getLogin());
        resource.setPassword(config.getPassword());

        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();

        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

我的电话:

String test = restTemplate.getForObject(URI.create(config.getBaseUrl() + "/configuration/all"), String.class);

有人可以解释如何设置resttemplate以便它与Https一起使用吗?

编辑:我尝试将包含站点证书的keystore.p12添加到应用程序中,但没有任何改变:

server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=xxx
server.ssl.key-password=xxx
server.ssl.trust-store=classpath:keystore.p12
server.ssl.trust-store-password=xxx

1 个答案:

答案 0 :(得分:0)

这是因为OAuth2RestTemplate上的AccessTokenProvider在内部创建了自己的RestTemplate以便请求令牌。为了设置该内部RestTemplate的提供程序,您可以执行以下操作(根据您正在执行的OAuth类型更改为不同类型的AccessTokenProviders)

ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);