Wednesday, 31 August 2016

How to use Authentication in MongoDB

I am using mongoDB version 3.2
By default authentication in mongoDB is disabled.

In order to enable authentication we need below prerequisites.
 Prerequisites:
1. Create role (or use In built roles)
2. Create user

Here ,I am going to create read access to admin db using in built role "read"

How to create User?
1. run mongod instance
  mongod
2.connect it using mongo shell
   mongo
3.connect to admin db
use admin
4.Now create user in this database.
db.createUser({user:"super",pwd:"super123",roles:["root"]});

 user- username
 pwd -password
 roles- read
db -admin (The scope of this access is limited to admin db by default because we are using "admin" db)
Now user has been created successfully.

How to authenticate?
5. close mongod instance and mongo shell and reconnect to enable authentication.
mongod --auth
6.connect to admin db
use admin 
7. now if you try to access this db you will be shown "Not Authenticated" message.
So, you need to get authenticated using user name and password.
    db.auth("super","super123")

Now you can access admin db for "read" operations.

No comments:

Post a Comment