0

I'm trying to configure a Spring Boot web application to use TLS when making connections to a MongoDB instance, running in a Docker container.

I've configured the MongoDB instance in Docker to use a self-signed certificate, and require TLS. The configuration file for MongoDB (mongod.conf) looks like this:

net:
  bindIp: 0.0.0.0
  port: 27017
  tls:
    certificateKeyFile: /home/mongodb/ssl/my-self-signed-cert.pem
    mode: requireTLS
    allowConnectionsWithoutCertificates: true
...

I can connect to the instance with TLS using the Mongo connection string from the command line, getting the Mongo shell. However, I can't get my web application to connect to that same MongoDB instance over TLS.

To try testing the connection, I've tried creating a unit test that will access the DB. The Spring Boot magic causes the test to fail during setup. It seems like this is because autowiring in some of the dependencies (MongoTemplate, I think) seems to test the connection, which requires TLS and then fails.

To set up the TLS connection, I added the server's certificate to the Java truststore, using keytool. However, the connection still fails. I've tried specifying the location of a .jks file created with keytool, as well, in the application.yml file, like so:

...
javax:
  net:
    ssl:
      trustStore: src/main/resources/truststore/trustedcerts.jks
...

Ultimately, my question is: How can I configure TLS-secured connections to MongoDB from my Spring Boot app? Currently, we implement data access using MongoRepository and MongoTemplate.

bun_at_work
  • 37
  • 1
  • 9

1 Answers1

0

You have to set the system properties in your java application

System.setProperty ("javax.net.ssl.keyStore",keystorePath);
System.setProperty ("javax.net.ssl.keyStorePassword",keystorePass);
System.setProperty ("javax.net.ssl.trustStore",truststorePath);
System.setProperty ("javax.net.ssl.trustStorePassword","changeit");
jpdoliveira
  • 15
  • 10
  • 1
    Could you explain that in more detail? What are these key/truststores and where can I get them? – Asdf11 Dec 11 '21 at 17:40
  • It's been a long time since I did this. But there are answers related to this here that explains it. https://stackoverflow.com/questions/2138574/java-path-to-truststore-set-property-doesnt-work – jpdoliveira Dec 13 '21 at 16:09
  • Thank you I found out that in the latest version its sufficient to add "?tls=true" in the end of the mongo db uri. This uri should also contain username:password. It is possible to use "mongodb+srv://" which has tls enabled by default. Although I did not try this approach. – Asdf11 Dec 17 '21 at 14:14