Tuesday, August 26, 2014

Mongo Authentication is really Simple :)

Lets talk about Mongo Auth. We know that an "authentication" should be based on username,password,roles, etc.

First start mongod without auth

sudo mongod

OR

service mongodb start

Then take mongo shell

$mongo
MongoDB shell version: 2.4.9
connecting to: test
> use admin
switched to db admin

>db.addUser('user','pass')
{
"user" : "user",
"readOnly" : false,
"pwd" : "e0c4a7b97d4db31f5014e9694e567d6b",
"_id" : ObjectId("53fc7c5f4e77b510f6f4046f")
}



Then, Start mongod instance in --auth mode.

sudo mongod --auth

OR

add auth=true in mongodb.conf in /etc/ and restart mongodb service.


Then take mongo shell

$mongo
MongoDB shell version: 2.4.9
connecting to: test
> use admin
switched to db admin

>show collections
Tue Aug 26 17:53:04.682 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:128

>db.auth('user','pass')
1

yeah...now you are authenticated.You can access all databases.

> db.logout()
{ "ok" : 1 }

Since admin database is a default in every mongodb and act as admin.Users in admin can access all databases.Another thing is admin user can set readOnly by passing 'true' as argument.


db.addUser('user','pass','true')


Important thing is,


In mongodb, Users are created for databases.

for example,if you want to create user for database 'testdatabase':


>use testdatabase
testdatabase

db.addUser('user','pass')


Here you are ready.You can add roles for users