Skip to Content

Spring - MongoDB connection with SSL/TLS configuration

Most of the cloud providers that propose Database as a service (DBaaS) enforces high-security requirements for the connections to their databases. One of them is Digital Ocean, where the connection needs to be SSL/TLS.

Firstly you need to download the certificate authority from the Digital Ocean console, and add the authority to a key store that will be used by the application.

keytool -import -alias cacert -storepass <password> -keystore cacerts.jks -file ca-certificate.crt

Once the key store is created, it can be used as below.

public class MongoDBConfiguration {

    private String mongoUri;

    private String password;

    private String truststore;
    public SSLContext mongoSSLContext() throws
            CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream in = new FileInputStream(truststore)) {
            ts.load(in, password.toCharArray());

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);

        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, tmf.getTrustManagers(), new SecureRandom());

        return sc;

    public MongoClient mongoClient(SSLContext sc) {
        return MongoClients.create(
                        .applyConnectionString(new ConnectionString(mongoUri))
                        .applyToSslSettings(builder -> {