Search code examples
javamongodbsslmongo-javamongo-java-driver

Mongo Java Client: How can I connect with SSL enabled but no certificate?


For testing I have setup a mongodb server which allows for ssl connections without certificate. I am able to connect in this way using RoboMongo and the mongo-c-driver, however when I try Java I get: {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}}

I tried setting the socket factory to use default socket but I get: com.mongodb.MongoInternalException: SSL is enabled but the socket is not an instance of javax.net.ssl.SSLSocket

How can I make this connection?


Solution

  • So based on general SSL and this answer by 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();
    }
    

    ```