How to secure mongo db by authentication

This article explains about how to secure mongo db by authentication

Hello all. Today we will see how to secure our mongo db. I am assuming you already have mongo db installed in your system else refer hereThe idea here is , we are going to create two users

  • admin user (have read and write access to all databases in mongo)
  • Database user (user who has access to specific database alone)

Step 1: Save this as auth.js

use admin

db.createUser({user: "admin",pwd: "adminpass",roles: [{ role: "userAdminAnyDatabase", db: "admin" }]});
use mytest;
db.createUser({user: "mytestadmin",pwd: "testadmin",roles: [ { role: "readWrite", db: "mytest" }]}) ;

Note: change {pwd, db } to your needs . Here   adminpass is my admin password.  mytest is my my test database , mytestadmin is user for mytest database alone .

Step 2: Run  auth.js and create user By

$ mongo < auth.js

Successfully added user: {
"user" : "mytestadmin",
"roles" : [
{
"role" : "readWrite",
"db" : "mytest"
}
]
}


It indicates, User Created  Successfully.

Step 3: Change Mongod.conf to Use auth

Open  mongod.conf and add this line

sudo nano /etc/mongod.conf

# add this lines 
security:
authorization: enabled

In order to changes to the configuration reflect we need to restart mongo db

Step 4: Restart Mongo db by

sudo systemctl restart mongod.service

Finally Check Auth working or Not

  Open terminal and enter

>mongo mytest
MongoDB shell version: 3.2.12
connecting to: mytest

Don't panic . By default mongo allows you to connect to any database . But they can't see anything .

Now fire this command

> show dbs
2017-02-24T17:41:17.784+0530 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:761:19
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1

Woo !!! Our auth Works fine . It Blocks viewing/writing to our database .

Now Let's Authenticate and issue commands

 >db.auth("mytestadmin", "testadmin")
1

which returns  1 in response means success !!!

Note: If your using pymongo or mongo engine or any other ORM to connect to Mongo , You need to pass username and password and method of auth in connection statement.

For example in mongo engine it looks like this !!!

db = mongoengine.connect("mytest", host="0.0.0.0", port=27017, username="mytestadmin", password="testadmin")


That's It . We Secured Our Mongo db. Hope it helps !!!

Thanks for Reading !!! Happy Coding !!!

Leave a comment

(Note: Comments are moderated)