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.
@Configuration
public class MongoDBConfiguration {
@Value("${spring.data.mongodb.uri}")
private String mongoUri;
@Value("${app.data.mongodb.truststore.password}")
private String password;
@Value("${app.data.mongodb.truststore.path}")
private String truststore;
@Bean
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);
tmf.init(ts);
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, tmf.getTrustManagers(), new SecureRandom());
return sc;
}
@Bean
public MongoClient mongoClient(SSLContext sc) {
return MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(mongoUri))
.applyToSslSettings(builder -> {
builder.context(sc);
})
.build());
}
}