Having the ability to authenticate users with your database is an important security feature. This is especially true when that database is storing sensitive information, such as user accounts for a website or company data.
With authentication enabled on your MongoDB instance, you can set specific rules about what user accounts are permitted to do and what sort of access they have. This also means that you can also lock down certain features so that only authorized users have access to them.
In this article, we will show you how to enable authentication in MongoDB so that only authorized users can access the database and its contents.
Create an Admin User
We will first create a user to manage all users and databases, and then we will create a MongoDB database owner with reading and write privileges on one database instance.
To manage all users and databases, create an admin user on your MongoDB server. Using Mongo shell, switch to the admin database and create a user.
use admin
db.createUser({ "user":"admin", "pwd":"admin_password", "roles":[ { "role":"root", "db":"admin" } ] })
Verify the authentication, run command on Mongo shell:
db.auth("admin", "admin_password")
The result “1” is for successful authentication.
Create Database Specific User
Now, set up a user for your application’s database. Use the “use” command to select your database, and then create a user with the following commands. You must change the database name, username, and password to the ones listed below.
use mydb
db.createUser({ "user":"db_user", "pwd":"your_password", "roles":[ { "role":"dbOwner", "db":"mydb" } ] })
Verify the authentication, run command on Mongo shell:
db.auth("db_user", "your_password")
The result “1” is for successful authentication.
Enabling Authentication on MongoDB
You have just created a user for your database. Now, flip the authentication switch to enforce login. To enforce authentication on your MongoDB server, edit /etc/mongod.conf in your preferred text editor.
sudo vim /etc/mongod.conf
Add/Edit the below lines to the configuration file
security: authorization: enabled
Save your file and close.
Then restart the MongoDB instance to apply the changes.
sudo systemctl restart mongod
All done!
Conclusion
You have secured your MongoDB server by enabling proper authentication on databases. MongoDB will reject all requests without authentication. Its also recommended to restrict Mongodb port 27017 via a firewall, whether it is provided by the cloud hosting or the system’s inbuild firewall.