Mongodb Enable Authentication

Start MongoDB without access control.

Connect to the instance using command line:


Once you are in the mongo shell, create the administrator user.

use admin
user: "user",
pwd: "password",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }

Exit the mongo shell, edit mongo.conf:
add below line under security:

authorization: enabled

Re-start the MongoDB instance and access control will be in place.

use command line to login and auth:

mongo --host --port 27017 -u "user" -p "password" --authenticationDatabase "admin"

Admin user can only manage users, it cannot perform CRUD unless readWrite role is granted. For security purpose, we seperate readWrite users and database admin using different users.

Next, create user for each database for CRUD operations:

use newdatabase
user: "user1",
pwd: "password1",
roles: [ { role: "readWrite", db: "newdatabase" } ]

Note: use newdatabase will create the new database "newdatabase" if it doesn't exist.

Be the first to comment

Leave a Reply

Your email address will not be published.