Password Protect MongoDB

At the very least you should set a password on your MongoDB deployment. This post will cover how to enable passwords for your MongoDB deployment, create an admin account, and add new accounts for a new database.mongodb

Step 1. Create an Admin Account

Before we password protect our deployment and close it off to the world, we’ll need to create an admin account which we can use to administer our deployment.

First we’ll need to open the MongoDB console. To do so, simply open your terminal and enter:

$ mongo

You should be placed into the MongoDB console. Now you’ll want to select the admin database. Select the collection by entering:

use admin;

Now you can add a new user to the admin database. This user should be added with full administration privileges. Consider this you root account if you’re coming from MySQL. Since we want this to be our root user, we’re going to assign the role of ‘userAdminAnyDatabase’ to this user. We can create this new user by issuing the following command (note, you’ll want to fill in the username and password with your own values):

db.createUser({ user: "adminUser", pwd: "adminpassword", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] });

You should see output similar to the following:

Successfully added user: {
"user" : "adminUser",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}

Now that we’ve added the admin user, we’ll want to test that the credentials work before enabling authentication. You can log in as this user by issuing the following command:

db.auth('yourUsername','yourPassword');

If everything wen’t as expected, you should see a ‘1’ output, indicating you authenticated successfully.

Step 2. Enable Password Authentication

Now that we have an admin account created we’ll want to enable authentication on the MongoDB deployment.

We can enable password authentication at the config level by modifying the MongoDB config file. On most systems this file will live at /etc/mongod.conf. Let’s modify this file to enable authentication.

$ sudo vi /etc/mongod.conf

To enable password authentication, we’ll need to uncomment the ‘security:’ section and add one property within this section. Your config should look similar to the following after you make this change:

...

# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.

security:
authorization: enabled

#operationProfiling:

#replication:

...

Note: In older versions of MongoDB you’ll be looking to uncomment the ‘#auth=true` line.

Save and exit. Now we can restart MongoDB with the following command:

$ sudo service mongod restart

After MongoDB restarts successfully authentication should be enabled.

Step 3. Testing Authentication

At this point we should have password authentication enabled for MongoDB. Next we’ll test that everything is working as expected by authenticating as our admin user we created previously.

Let’s try authenticating with the admin account we created previously. First we’ll need to open the mongo console:

$ mongo

You should notice that you don’t immediately have access to everything now. If you even try typing the ‘show dbs’; command you’ll notice you don’t have access and will receive the following error:

> show dbs;
2017-11-26T15:27:06.585-0500 E QUERY    [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
[email protected]/mongo/shell/utils.js:25:13
[email protected]/mongo/shell/mongo.js:62:1
[email protected]/mongo/shell/utils.js:781:19
[email protected]/mongo/shell/utils.js:671:15
@(shellhelp2):1:1

Let’s try logging in to our admin user account. First select the database:

use admin;

Now authenticate with your username and password:

db.auth('yourUser','yourPassword');

You should see a ‘1’ output, meaning you authenticated successfully. Now you can issue the ‘show dbs;’ command and it will actually work!

Step 4. Adding a New Database User

It’s good practice to limit the privileges your user has to what is appropriate. Therefore, we’ll demonstrate making a new user that has full access to a single database.

We don’t want to use our admin account for things other than administration, so let’s create a new user with full access to a single database. I’m assuming since you followed the previous steps that you know how to log in to your MongoDB instance as an admin, so do that now. Once we’re logged in, let’s now create the new database and then the new user to own it (notice that we’re assigning the ‘dbOwner’ role to this owner. This will give this account all permissions to the database):

> use newDb;
switched to db newDb
> db.createUser({ user: "newDbUser", pwd: "password", roles: [{ role: "dbOwner", db: "newDb" }]});
Successfully added user: {
"user" : "newDbUser",
"roles" : [
{
"role" : "dbOwner",
"db" : "newDb"
}
]
}

That’s it. You should have a new user that has full access to the newDb database. Log out and then test logging in by selecting the newDb via:

use newDb;

Then authenticate the user against this db by issuing the following command:

db.auth('yourUser', 'yourPassword');

You should see a ‘1’ output, indicating your authenticated successfully.

It’s good practice to create at least one separate user for each database your create, so you can repeat this final steps each time your create a new database to ensure it’s password protected and not open to the world.

That’s all there is to it. You should now have a password protected MongoDB deployment with an admin account with full access for administration. Don’t forget to create new accounts for new databases to keep permissions appropriate and only use the admin account for administration.

Ref : Link