Learn the root cause and solution to fix the authentication error caused when connecting with MongoDB from a Spring boot application.
1. Problem
We get the AuthenticationFailed error when we are trying to connect to MongoDB either running standalone or inside a docker container from a Spring boot application using the following properties. The property values might be different in your case:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testdb
spring.data.mongodb.username=mongoadmin
spring.data.mongodb.password=secret
Note that we started the mongo docker container with the following command in our case:
$ docker run -d -p 27017:27017 --name mongo-on-docker \\
-e MONGO_INITDB_ROOT_USERNAME=mongoadmin \\
-e MONGO_INITDB_ROOT_PASSWORD=secret \\
-e MONGO_INITDB_DATABASE=testdb \\
mongo
This command creates a new user with the name “ mongoadmin ” and password “ secret ” into the default database “admin”. The main purpose of this ‘ admin ‘ database is to store system collections and user authentication and authorization data, which includes the administrator and user’s usernames, passwords, and roles.
In our application.properties file, we have not mentioned the database name where the user details are located for authentication, we get the authentication failed error.
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating
MongoCredential{mechanism=SCRAM-SHA-1, userName='mongoadmin', source='testdb', password=<hidden>, mechanismProperties=<hidden>}
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed):
'Authentication failed.' on server localhost:27017. The full response is
{"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
...
2. Solution
2.1. Use Admin Database
To fix this error, we need to, additionally, provide the ‘ authentication-database ‘ property in the configuration as follows:
spring.data.mongodb.authentication-database=admin
The complete set of properties for authentication is:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testdb
spring.data.mongodb.username=mongoadmin