一尘不染

忽略Servlet中的SSL证书

tomcat

我收到以下异常:

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

我做了一些研究,并更改了连接代码:

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

CloseableHttpClient client = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy()) 
            .setSslcontext(sslContext)   
            .setConnectionManager(connMgr)
            .build();

到目前为止,这已解决了该问题,我不再遇到异常并且连接正常。

当我在Tomcat中运行的Servlet中使用相同的代码时,问题再次出现。

为什么呢


阅读 234

收藏
2020-06-16

共1个答案

一尘不染

请尝试以下代码。

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class DummyX509TrustManager implements X509TrustManager {

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    @Override
    public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
            throws CertificateException {
    }

    @Override
    public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
            throws CertificateException {
    }
};


final TrustManager[] trustAllCerts = new TrustManager[] { new DummyX509TrustManager() };
try {
    SSLContext sslContext= SSLContext.getInstance("SSL"); 
    sslContext.init(null, trustAllCerts, null);

    CloseableHttpClient client = HttpClients.custom()
        .setRedirectStrategy(new LaxRedirectStrategy()) 
        .setSslcontext(sslContext)   
        .setConnectionManager(connMgr)
        .build();
} catch (KeyManagementException e) {
    throw new IOException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
    throw new IOException(e.getMessage());
}
2020-06-16