Add new MongoDB user

Table of Content

Suppose, your have site with Mongo and you want user can connect to this with login and password.

Step 1.
Enable authentication in /etc/mongodb.conf

auth=true

Step 2.
Create the system user administrator. Connect to mongo and execute next command:

$ mongo

 

db.createUser(
  {
    user: "admin",
    pwd: "yourSuperPass",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

Explain from documentation:

After you create the user administrator, the localhost exception is no longer available.

The mongo shell executes a number of commands at start up. As a result, when you log in as the user administrator, you may see authentication errors from one or more commands. You may ignore these errors, which are expected, because the userAdminAnyDatabase role does not have permissions to run some of the start up commands.

Step 3.
Restart MongoDB

$ service mongod restart

Step 4.
Try connect:

mongo --port 27017 -u admin -p yourSuperPass --authenticationDatabase admin

Step 5.
Create additional users (documentation).
Create the user in the database to which the user will belong. Pass a well formed user document to the db.createUser() method.

The following operation creates a user in the reporting database with the specified name, password, and roles.

use reporting
db.createUser(
    {
      user: "reportsUser",
      pwd: "12345678",
      roles: [
         { role: "readWrite", db: "accounts" }
      ]
    }
)

To authenticate the reportsUser, you must authenticate the user in the reporting database.

Read also:

Leave a Reply

Your email address will not be published. Required fields are marked *