Procedures
Follow instruction in reference #1 to create an administrator user
1 | use admin |
Create non-administrator users
Once the administrator is created, restart mongod with option --auth
enabled, and connect to it using
1 | mongo -u superuser -p supercool --authenticationDatabase admin |
Let’s say we are going to have a new database named app
and we need to create a user to access that. We can either issue use admin
or use app
before the db.createUser
command. Here comes the first note about mongodb authentication: by issuing use app
, it doesn’t mean the user (details) will be created in database app
, instead, all users information will be stored in system.users
collection of admin
db. The result of command use admin
or use app
only serves as an identification purpose for non-administrator user creation, nothing else. Because of this reason and it might be a bit easier for user management, I would suggest that admin
be used for all users. Therefore, run the following commands:
1 | use app |
To test if the user is created successfully, exit mongo shell and issue a new one
1 | mongo -u appUser -p appPass --authenticationDatabase admin app |
The last command should show the collection list
created by superuser
in previous mongo shell session. To ensure user appUser does have the read/write privilege in db app
,
1 | db.find() |
Note: Since user appUser
is configured to allow access to only db app
, if you issue show databases
command, only app
would return, and that’s also the reason app
needs to be specified in the mongo
command.
A complete note.js example
1 | const MongoClient = require('mongodb').MongoClient |
Note: option authSource
is used to specify authenticationDatabase
.
References:
MongoDB Manual on authentication.
SO entry on which authentication database to use