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 MongoDB server to accept request from your local area network only, but still there are chances for the hacker to inject malicious script to your server. So its 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 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 user.

use admin
db.createUser({ user: "admin", pwd: "admin_password", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })

Verify the authentication, run command on Mongo shell:

db.auth("admin", "admin_password")

Create Specific Database User

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

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")

Enabling Authentication on MongoDB

You have successfully created 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.

The post How to Enable Authentication in MongoDB Instance appeared first on TecAdmin.

authentication mongo MongoDB