代码之家  ›  专栏  ›  技术社区  ›  Smajl

使用OAuth2RestTemplate请求HTTPS资源

  •  1
  • Smajl  · 技术社区  · 6 年前

    我试图从一个用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
    

    这是我的restemplate配置:

    @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);
    

    有人能解释一下如何设置restemplate使其与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
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Will M.    5 年前

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

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