How to Enable Authentication in MongoDB Instance

How to Enable Authentication in MongoDB Instance

 

How to Enable Authentication in MongoDB Instance


The default MongoDB install with no password for accessing databases. You can enforce authentication in the MongoDB server to add an extra layer of security. You may have controlled the MongoDB server to accept requests from your local area network only, but still, there are chances for the hacker to inject malicious script into your server. So it's recommended to keep your server protected with a username and password and database roles.

In this tutorial, you will learn to create users for your MongoDB databases and assign them specific roles.

Create Admin User

In the first place, we will create a user (in this case, it’s admin) for managing all users and databases and then we will create a specific database owner having only read and write privileges on one MongoDB database instance.

Create an admin user on your MongoDB server to manage all users and databases. Connect to Mongo shell and switch to the admin database and create a user.

and switch to the admin database and create user.

Verify the authentication, run the command on Mongo shell:

Create Specific Database User

Next, create a user for your application database. Select your database using “use” command and then create a user with the following commands. You need to change the database name, username, and password to the below commands.


Verify the authentication, run command on Mongo shell:

Enabling Authentication on MongoDB

You have successfully created a user for your database. Now, toggle the authorization setting to enforce authentication. To enable the authentication on MongoDB instance, Edit mongod.conf file in your favorite text editor.

vim /etc/mongod.conf

Add/Edit below lines to the configuration file

security:
      authorization: enabled

Save your file and close.

Then restart the MongoDB instance to apply the changes.

service mongod restart

Conclusion

All done!. You have secured your MongoDB server by enabling proper authentication on databases.

Reactions

Post a Comment

0 Comments

close