Mongo Java Client:如何连接启用SSL但没有证书?

时间:2017-05-11 09:50:25

标签: java mongodb ssl mongo-java mongo-java-driver

为了进行测试,我设置了一个mongodb服务器,允许没有证书的ssl连接。我可以使用RoboMongo和mongo-c-driver以这种方式连接,但是当我尝试Java时,我得到: {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}, caused by {sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}, caused by {sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}}

我尝试将套接字工厂设置为使用默认套接字,但我得到: com.mongodb.MongoInternalException: SSL is enabled but the socket is not an instance of javax.net.ssl.SSLSocket

如何建立此连接?

1 个答案:

答案 0 :(得分:-2)

因此基于一般SSL和ZZ Coder的this answer

MongoClient mongoClient = new MongoClient(serverAddress, 
Collections.singletonList(mongoCredential), MongoClientOptions.builder().sslEnabled(true).socketFactory(getNoopSslSoketFactory()).build());


private static SSLSocketFactory getNoopSslSocketFactory() {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }}, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        LOG.error("Couldn't create SSL Context for MongoDB connection", e);
        throw new RuntimeException(e);
    }
    return sslContext.getSocketFactory();
}

```