Skip to main content

Use Spring Data to connect to MongoDB using SSL connection.

This post is in continuation to my earlier post on How to enable SSL in MongoDB Community version. Once we have enabled SSL connection on MongoDB server, how can we connect to MongoDB server using Spring Java application.

In a Spring application connection to MongoDB is controlled by MongoClient and MongoClientOptions classes.

Follow below steps to connect Java Spring application running on Windows server to a MongoDB instance using secure SSL connection.

1. Copy client-cert.crt and mongodb-cert.crt files to Client machine.

You need to copy client-cert.crt and mongodb-cert.crt files used for setting up MongoDB server to machine that will be running your Spring application. (Refer: How to enable SSL in MongoDB Community version)

2. Import client and server certificate files to keystore.

Use below command to import MongoDB certificate.
keytool -import -alias "MongoDB-cert" -file C:\Users\abc\ssl\mongodb-cert.crt -keystore truststore.ts -noprompt
and below command to import Client certificate.
keytool -import -alias "Client-cert" -file C:\Users\abc\ssl\client-cert.crt -keystore client.ts -noprompt
3. Application Configuration

We use SSLSocketFactory to establish secured SSL connection.
public class SSLMongoConnection {

    public static void sample() throws KeyManagementException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        InputStream readStream = new FileInputStream("C:\\Users\\abc\\ssl\\clientstore.ts");
        KeyStore ksClient = KeyStore.getInstance("JKS");
        ksClient.load(readStream, "<password>".toCharArray());
        Key key = ksClient.getKey("client-cert", "<password>".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ksClient, "<password>".toCharArray());
        KeyStore ksCACert = KeyStore.getInstance(KeyStore.getDefaultType());
        ksCACert.load(new FileInputStream("C:\\Users\\abc\\ssl\\truststore.ts"), "<password>".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        SSLContext context = SSLContext.getInstance("TLS"); //We now provide our alternate KeyManager
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        SSLSocketFactory sslSocketFactory = context.getSocketFactory();

        MongoClientOptions mongoClientOptions = MongoClientOptions.builder().socketFactory(sslSocketFactory).maxConnectionIdleTime(120000).socketKeepAlive(true).build();

        MongoClient mongoClient = new MongoClient(new ServerAddress("<host-name>", 27017),
                singletonList(MongoCredential.createCredential("<username>", "<database>", "<password>".toCharArray())));

        //use mongoClient to execute queries