Mongodb Enable Authentication

Start MongoDB without access control.

Connect to the instance using command line:

mongo

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

use admin
db.createUser(
{
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:

security:
authorization: enabled

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

use command line to login and auth:

mongo --host 10.0.0.1 --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
db.createUser(
{
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.


*