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.

1

2

use admin

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

Verify the authentication, run command on Mongo shell:

1

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.

1

2

use mydb

db.createUser({ user: “db_user”, pwd: “your_password”, roles: [{ role: “dbOwner”, db: “mydb” }] })

Verify the authentication, run command on Mongo shell:

1

db.auth(“db_user”, “your_password”)

#mongodb #authentication #mongo #mongodb

How to Enable Authentication in MongoDB Instance – TecAdmin
1.60 GEEK