Setting up authentication for MongoDB on Ubuntu

Posted By : Akash Sharma | 08-Feb-2014

In this blog I am going to share the details of how to authenticate mongodb while logging to database in ubuntu environment.

Before going further I assume that you have already setup mongodb on your ubuntu machine.If not, you can follow this link

 

To make mongodb as authenticated login, we have to configure parameter auth=true in /etc/mongodb.conf file.

Before making this configuration, we have to create a user with required role that can easily login in authenticated development environment and do required operations.

For getting information about all the roles of a user follow this link

The two important roles for a user are userAdmin and userAdminAnyDatabase .

The userAdmin role is a database-specific privilege, and only grants a user the ability to administer users on a single database.

userAdminAnyDatabase provides users with the same access to user administration operations as userAdmin, except it applies to all logical databases in the MongoDB environment.

 

In this blog I have taken

database name = myDB

username = myUsername

password = myPassword

 

First you have to add a user with required privileges.If you have already a database with some user credentials then your own username and password.

Open a terminal and hit following commands:

mongo
>db = db.getSiblingDB('admin')
>db.addUser( { user: "myUsername",pwd: "myPassword",roles: [ "userAdminAnyDatabase" ] } )

 

If you have already created a database before, then do not need to hit following commands.

>use myDB
switched to db myDB
>db.addUser("myUsername","myPassword")
{
       "_id" : ObjectId("51e39ba329e0772d7de869be"),
       "user" : "myUsername",
       "readOnly" : false,
       "pwd" : "60c55b23692da72cf223712b8bfd614f"
}
>

 

Now you need to stop the mongodb service.

sudo service mongodb stop

 

Now add or uncomment following line from /etc/mongodb.conf file

auth=true

 

Now restart mongodb service

sudo service mongodb start

 

Now try to login into database

mongo -u myUsername -p myPassword localhost/myDB

 

For more information on authenticated login follow these two links: link1 link2

 

Thanks

 

About Author

Author Image
Akash Sharma

Akash is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Akash loves playing Cricket and Tennis

Request for Proposal

Name is required

Comment is required

Sending message..