Friday, May 15, 2015

Creating user with authentication in mongodb.

1.Start mongodb server
 ./mongod --dbpath datbaseDir  

2.Start mongo client command line interface.

3.Create admin user for all databases.
 >use admin  

4.Press CTRL+C

5.Now type
 mongo --port 27017 -u adminDatabase -p 123 --authenticationDatabase admin  

6.Now it will jump to prompt with adminDatabase user as logged in user.Now assume that you want to create new database newTest and want to create a admin user mahesh for it.Assume that mahesh must be able to add new user for database newTest.Steps are given below
 > use newTest  
 switched to db newTest  
 > db.createUser({user:"mahesh",pwd:"123",roles:[{role:"userAdmin",db:"newTest"}]})  

Now you can logged in using mahesh user.
 mongo newTest --port 27017 -u mahesh -p  

But if you try to create document using mahesh user it will show the error.
 > db.doc1.insert({"name":"shailesh"})  
     "writeError" : {  
         "code" : 13,  
         "errmsg" : "not authorized on newTest to execute command { insert: \"doc1\", documents: [ { _id: ObjectId('5555991b5102d7a82ac1daef'), name: \"shailesh\" } ], ordered: true }"  

It is because the permissions given to mahesh.Mahesh can just create new user not new collection.

7.Lets create new user on same database newTest but with read and write permissions.Logged in again with mahesh user.
 mongo newTest --port 27017 -u mahesh -p  
 > db.createUser({user:"mahesh1",pwd:"123",roles:[{role:"readWrite",db:"newTest"}]})  

Now mahesh1 can easily insert document into newTest.

No comments:

Post a Comment