1

If you want to add authentication to a MongoDB database to allow only allowed users to access it with specific rights allowed to each. How to get started?

1 Answers1

3

Here is how one can create their first user and attach them to admin role.

While creating a user add the third argument as an array of role names. See the following done in shell:

sudo mongod --auth

In new terminal run the following:

mongo
use admin
db.createUser({user: "myname", pwd: "mypass", roles: ["userAdminAnyDatabase"]})

User then can log in with their credentials that we just registered with the following expression:

db.auth("myname", "mypass")

Alternatively ypu can use the following method to log in:

mongo -u myname -p mypass --authenticationDatabase admin

If you want to create a user to have access to just one particular database the follow this expression: Go into the database

use mydb

Create user and assign a role

db.createUser({user: "yourname", pwd: "yourpass", roles: ["readWrite"]})

Now logout from first admin user

db.logout()

Login with the new user

mongo -u yourname -p yourpass --authenticationDatabase mydb

Get into the mydb database

use mydb

Then you can perform read and write operations on mydb database

db.mycollection.insertOne({name: "Vinit Khandelwal"})

Here is a bonus: Update user roles and database access

  1. Logout and login with admin of admin database
  2. Get into mydb database

Then run the following:

db.updateUser("mydb", {roles: ["readWrite", {role: "readWrite", db: "yourdb"}]})

This gives the user a readWrite access to mydb as well as to yourdb database

  • 1
    MongoDB allows the first user to be made without authentication from localhost only. –  Sep 29 '19 at 20:16