The username and password are the most basic form of authentication. By default, MongoDB does not provide any form of authentication. This means that any user with access to your MongoDB Server interface can access and manage your database.
This is a severe security risk, especially when exposing your database to the world. Therefore, this post will show you how to configure the username and password authentication in the MongoDB server.
Let’s jump into it.
Step 1: Login to MongoDB Server
The first step is to login into your server. Since MongoDB is not secured, you can run the following command:
The given command logs into the MongoDB server with the default username.
Step 2: Change to Admin Database
Next, change into the admin database which allows us to perform the actions such as creating new users and assigning permission.
'switched to db admin'
Step 3: Create Administrator User
The next step is to create a user with the UserAdminAnyDatabase role. This allows you to manage any database on the server.
We can run the command as follows:
Running the previous command should create a username called root with the specified password and userAdminAnyDatabase role.
Output:
Step 4: MongoDB Enable Authentication
Once we created a username and password, we need to enable the authentication for the MongoDB server.
We can do this by editing the MongoDB configuration file. Keep in mind that the location to the MongoDB configuration file differs depending on the installation method and operating system.
Locate the mongod.conf or mongod.cfg file in your system. Edit the file with your favorite text editor:
Edit the file and locate the entry as shown in the following:
authorization: "disabled"
In some cases, you may find the security block commented out as shown in the following:
Uncomment by removing the preceding pound sign and set the entry as shown in the following:
authorization: "enabled"
Save the file and close.
Restart the MongoDB service with the following command:
On Windows, you can run the following command:
Run the following command to login into the server with the specified username and password:
Conclusion
This post discussed the basics of setting up a username and password authentication on a MongoDB Server.
Thanks for reading!