Command failed with error 18 (AuthenticationFailed)
本文最后更新于:2023年9月7日 下午
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:
1 |
|
Note that we started the mongo docker container with the following command in our case:
1 |
|
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.
1 |
|
var adpushup = window.adpushup = window.adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(“4f41e429-fdc3-445a-ae1b-2547bb0bb694”); });
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:
1 |
|
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
spring.data.mongodb.password=secret
spring.data.mongodb.authentication-database=admin
After providing this property, we will not get the error and authentication will be successful.
2.2. Verify Username and Password in Mongo Shell
If you are still getting the authentication issues, then it is worth verifying the username and password values. For this, you can connect to MongoDB using these credentials from the command line/terminal.
To connect to the mongo shell and authenticate, run the following commands. The large number is the container id.
$ docker exec -it 3248a6f47cebdd25aaab3a9244e85918e2339c07ffd78967b63a5d7bd8766618 mongosh
$ use admin
$ db.auth( 'mongoadmin', 'secret' )
If the credentials are not correct, we will get the respective errors.
3 Conclusion
In this short Java tutorial, we learned the possible causes and solutions for authentication failed error when connecting to MongoDB from a Spring boot application.
Happy Learning !!