当前位置: 首页 > 知识库问答 >
问题:

如何用Spring RestTemplate禁用SSL证书检查?

弓宏茂
2023-03-14

我正在尝试编写一个集成测试,其中我们的测试使用Simple启动一个嵌入式HTTPS服务器。我使用keytool创建了一个自签名证书,并且能够使用浏览器(特别是Chrome)访问服务器,并且我确实收到了关于自签名证书的警告。

但是,当我尝试使用Spring RestTemplate进行连接时,我得到了一个ResourceAccessException:

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8088":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
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:557)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:444)
    at net.initech.DummySslServer.shouldConnect(DummySslServer.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: 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
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
    at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:78)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:541)
    ... 33 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1351)
    ... 47 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
    ... 53 more
private static final HostnameVerifier PROMISCUOUS_VERIFIER = ( s, sslSession ) -> true;
HttpsURLConnection.setDefaultHostnameVerifier( PROMISCUOUS_VERIFIER );
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory( new SimpleClientHttpRequestFactory() {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        if(connection instanceof HttpsURLConnection ){
            ((HttpsURLConnection) connection).setHostnameVerifier(PROMISCUOUS_VERIFIER);
        }
        super.prepareConnection(connection, httpMethod);
    }
});
  1. 在单元测试之外的本地安装证书不是一个选项,因为这样就需要在每台开发计算机和生成服务器上手动安装证书,这将导致大量繁文缛节。
  2. 我们需要SSL,因为我们正在测试一个位于RestTemplate之上的库,并且我们正在正确配置它。

我使用的是Java8(但也可以使用7)和Spring4.0.3。

共有1个答案

支华池
2023-03-14

我希望我仍然有一个链接到源代码,引导我在这个方向,但这是代码,最终为我工作。通过查看X509TrustManager的JavaDoc,可以看到trustmanager的工作方式,即在验证成功时不返回任何内容,否则抛出异常。因此,对于空实现,它被视为成功的验证。然后删除所有其他实现。

import javax.net.ssl.*;
import java.security.*;
import java.security.cert.X509Certificate;

public final class SSLUtil{

    private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers(){
                    return null;
                }
                public void checkClientTrusted( X509Certificate[] certs, String authType ){}
                public void checkServerTrusted( X509Certificate[] certs, String authType ){}
            }
        };

    public  static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
        // Install the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init( null, UNQUESTIONING_TRUST_MANAGER, null );
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
        // Return it to the initial state (discovered by reflection, now hardcoded)
        SSLContext.getInstance("SSL").init( null, null, null );
    }

    private SSLUtil(){
        throw new UnsupportedOperationException( "Do not instantiate libraries.");
    }
}
 类似资料:
  • 问题内容: 我正在尝试编写一个集成测试,其中我们的测试使用Simple启动一个嵌入式HTTPS服务器。我使用创建了自签名证书,keytool并能够使用浏览器(特别是Chrome浏览器)访问服务器,并且收到有关自签名证书的警告。 但是,当我尝试使用Spring RestTemplate进行连接时,出现ResourceAccessException: 从其他问题和博客 文章中,我已经看到了Hostna

  • 问题内容: 从詹金斯(Jenkins)创建工作时,出现以下错误。如何在Jenkins中禁用证书验证? 在Git Bash中,我可以使用命令来禁用它,但不确定如何从Jenkins使用它。 错误: 问题答案: 最好的选择是将自签名证书添加到您的证书存储中 获取服务器证书树这可以使用chrome完成。 导航到服务器地址。单击挂锁图标并查看证书。将所有证书链导出为base64编码文件(PEM)格式。 将证

  • 问题内容: 该Web服务基于SSL且具有自签名证书,该证书托管在远程系统中。我已经创建了一个访问该Web服务的客户端。这是通过以编程方式将证书添加到密钥存储区来完成的 。 现在,我听说,不必为添加自签名Web服务而将证书添加到密钥存储中。 相反,我们可以通过覆盖某些方法来禁用证书检查。 这是真的?这些方法有哪些? 请帮忙。 问题答案: 这应该足够了。在针对没有适当签名的证书的测试和登台服务器测试代

  • web服务是SSL上的rest并且它有自己签名的证书,托管在远程系统中,我已经创建了一个访问该web服务的客户机。这是通过以编程方式将证书添加到密钥存储区来完成的。 现在我听说,访问自签名web服务不需要将证书添加到密钥存储区。相反,我们可以通过重写一些方法来禁用证书检查。这是真的吗?那些方法是什么?请帮忙。

  • 我已经看到了许多关于这个主题的帖子,但我无法解决这个问题,所以我发布了我的设置,以防有人知道需要更改什么? > 我有一个通过namecheap购买的域。我已经设置了自定义DNS,并添加了4个由AWS路由53中的托管区域生成的名称服务器。通过WHOIS.NET的DNS查找显示正确的值。 在路由53中,我在别名目标中添加了一条A记录,这样流量就会到达路由53并转到Cloudfront。 在CloudF

  • 但是我得到一个request.exceptions.SSLerror。网站有一个过期的证书,但我没有发送敏感数据,所以对我来说没关系。我会想象有一个像“verifiy=false”这样的论点我可以使用,但我似乎找不到它。