我正在尝试从受 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
最佳答案
这是因为 OAuth2RestTemplate 上的 AccessTokenProvider 在内部创建了自己的 RestTemplate 以请求 token 。为了设置该内部 RestTemplate 的提供程序,您可以执行以下操作(根据您正在执行的 OAuth 类型更改为不同类型的 AccessTokenProvider)
ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);
关于java - 使用 OAuth2RestTemplate 请求 HTTPS 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54129675/