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. Verify the authentication, run command on Mongo shell: 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. Verify the authentication, run command on Mongo shell: 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. Add/Edit the below lines to the configuration file Save your file and close. Then restart the MongoDB instance to apply the changes. 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.