By default, MongoDB has authentication disabled. To enable authentication in MongoDB we need to create a user and also have to change the config file. In this post, we will learn step by step to enable authentication in MongoDB.
After installing and starting the MongoDB you can directly access it with the following command:
mongosh
Now, let’s create a root
(which is super) user so that we can manage our MongoDB database and also can log in after enabling authentication.
After opening the mongo cell. Let’s list all the databases with the following command:
show dbs
The output should look like:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Now, let’s use the admin database.
> use admin
switched to db admin
Now we are inside admin database. All the root level users can be created inside this database. So, let’s create a root user with following query:
db.createUser(
{
user: "root",
pwd: "my_secured_password",
roles: [ { role: "root", db: "admin" } ]
}
)
In the above query, we have defined the following things:
- Username: root
- Password: my_secured_password
- Role: root
- Database: admin
This means, create a user root with the password my_secured_password. And assign a root level role inside admin database.
We’ve successfully created a root user. Now let’s enable authentication.
To enable authentication, you have to edit the config file which should be in /etc/mongod.conf
.
You can use any tool to edit this file. I would prefer to use vim. Hence, use the following command to edit:
sudo vim /etc/mongod.conf
The above command opens the file and you have to press Insert key to make it editable.
I assume you pressed the Insert key.
Then, paste the following property:
security:
authorization: enabled
Now, you can save these changes with the following step:
- Press Esc key
- :!wq // It writes the changes and quits the edit mode.
Restart the server with the following command:
sudo systemctl restart mongo
Now, when you try to access MongoDB with a mongo
command, you can access it but you can’t see any existing databases. Because the database is protected.
When you try to list the databases using the command:
show dbs
You will see a message like given below:
MongoServerError: command listDatabases requires authentication
Hence, to access the database you have to log in with credentials using the command below:
mongo -u root -p --autnenticationDatabase admin
After executing the above command you may prompt to enter the password.
Enter a password and you should be able to access your MongoDB server with authentication.
Done!
Congratulations! You have successfully enabled authentication in the MongoDB server.