在 Spring RestTemplate 中禁用 SSL 证书验证

新手上路,请多包涵

我在两台不同的机器上有两个基于 Spring 的 Web 应用程序 A 和 B。

我想从 Web 应用程序 A 到 Web 应用程序 B 进行 HTTPS 调用,但是,我在机器 B 中使用的是自签名证书。所以我的 HTTPS 请求失败了。

在 Spring 中使用 RestTemplate 时如何禁用 HTTPS 证书验证?我想禁用验证,因为 Web 应用程序 A 和 B 都在内部网络中,但数据传输必须通过 HTTPS 进行

原文由 Prabhu R 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

需要添加的是自定义 HostnameVerifier 类绕过证书验证返回true

 HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
});

这需要适当地放置在您的代码中。

原文由 Raghuram 发布,翻译遵循 CC BY-SA 4.0 许可协议

@Bean
public RestTemplate restTemplate()
                throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    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);
    return restTemplate;
 }

原文由 DanieleDM 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题