在Spring Rest模板中跳过SSL证书验证

使用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值