web analytics

Authentication in mongodb

Mysql databases allow username and password. Similarly if you require to keep authentication for your mongodb database as well, please do the following. Suppose, I have a database named abc, and I need to create a user named abc with password abc123.

First, create an admin user.

root@abc:~# mongo
MongoDB shell version: 2.4.10
connecting to: test
> use admin
> db.addUser("admin", "admin")

> use abc                   (Switch to the database abc)

> db.addUser("abc", "abc123")

Quit the mongoshell and stop mongo

root@abc:~# /etc/init.d/mongodb stop

root@abc:~# vi /etc/mongodb.conf    and make the following change

auth = true

root@abc:~#/etc/init.d/mongodb start

Now we need to test if authentication works. Which means, if not authenticated, you should not be able to saw the details of the database.

root@abc:~# mongo
MongoDB shell version: 2.4.10
connecting to: test

> use abc

> show collections

"$err" : "not authorized for query on abc.system.namespaces",
"code" : 16550

Now it shows the error that you are not authorized to view the collections. Now, authenticate with the details you created earlier and try.

> db.auth("abc", "abc123")
> show collections
 testcollection
 system.indexes
Once the authentication is done, the collections are listed. This is how you create a user for mongodb database.

Leave a reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>