为了测试,我设置了一个 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},由 {sun.security. validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径},由{sun.security.provider.certpath.SunCertPathBuilderException:无法找到有效证书路径引起要求的目标}}
我尝试将套接字工厂设置为使用默认套接字,但我得到:
com.mongodb.MongoInternalException: SSL 已启用但套接字不是 javax.net.ssl.SSLSocket 的实例
我怎样才能建立这种联系?
最佳答案
所以基于通用SSL和this answer作者:ZZ Coder
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();
}
```
关于java - Mongo Java 客户端 : How can I connect with SSL enabled but no certificate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43911999/