Posted by : at

Category : mongodb

Using Mongodb in Ubuntu 16.04 LTS access control with auth

http://docs.mongodb.org/manual/tutorial/add-user-administrator/

Connect to mongod shell using :

mongod –port 27017 –dbpath /var/lib/mongodb

Open a new terminal and Connect to mongo shell using :

mongo –port 27017

In the admin database,create a admin user (Replace user and pwd fields) :

use admin db.createUser( { user: “sujaykundu777”, pwd: “pass123”, roles: [ { role: “root”, db: “logs” } ] } )

use test db.createUser( { user: “sujaykundu777”, pwd: “pass123”, roles: [ { role: “readWrite”, db: “logs” } ] } )


use test db.createUser( { user: “tester”, pwd: “password”, roles: [ { role: “read”, db: “test1” }, { role: “read”, db: “test2” }, { role: “read”, db: “test3” }, { role: “readWrite”, db: “test” } ] } );

Shell into mongodb with the test user 1

mongo -u tester -p –authenticationDatabase test


Disconnect the mongoshell

Restart the mongod instance using auth

mongod –auth –port 27017 –dbpath /var/lib/mongodb

Connect and authenticate as the user administrator.

Using the mongo shell, you can:

Connect with authentication by passing in user credentials, or
Connect first withouth authentication, and then issue the db.auth() method to authenticate.

To authenticate during connection

Start a mongo shell with the -u , -p , and the --authenticationDatabase command line options:

mongo –port 27017 -u “myUserAdmin” -p “abc123” –authenticationDatabase “admin”

Otherwise in case of problems in sudo service mongod start

Remove the temporary socket: rm /tmp/mongodb-27017.sock
Restart mongo daemon with sudo: sudo service mongod restart

Add auth options in /etc/mongod.conf and restart mongod

security: authorization: enabled