使用Spring Rest模板时如何跳过SSL证书验证? 配置Rest Template,以便它使用Http Client创建请求。
注意:如果您熟悉sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
则下面的内容应该sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
您有所帮助。
Http客户端
首先,将HttpClient
(> 4.4)导入到您的项目中
compile('org.apache.httpcomponents:httpclient:4.5.1')
配置RestTemplate
使用Http客户端的SSLContexts
工厂方法配置SSLContext
:
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();HttpComponentsClientHttpRequestFactory requestFactory =new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);RestTemplate restTemplate = new RestTemplate(requestFactory);
org.apache.http.ssl.TrustStrategy
用于覆盖标准证书验证过程。 在上面的示例中-它始终返回true
,因此无需进一步验证即可信任证书。
考试
@Test
public void opensSSLPage() throws Exception {String uri = "https://some-secured-page.com";ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class);assertThat(entity.getStatusCode().is2xxSuccessful()).isTrue();
}
最后的话
上面的代码在某些情况下会有所帮助(例如,对具有自签名证书的服务器进行测试),但是不应在生产中使用它-除非您100%确信自己在做什么。
翻译自: https://www.javacodegeeks.com/2016/02/skip-ssl-certificate-verification-spring-rest-template.html