mongodb authentication by example

Procedures

Follow instruction in reference #1 to create an administrator user

1
2
3
4
5
6
7
8
use admin
db.createUser(
{
user: "superuser",
pwd: "supercool",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
use app
db.list.insertOne({
title: 'learn mongodb authentication'
})

use admin
db.createUser(
{
user: "appUser",
pwd: "appPass",
roles: [ { role: "readWrite", db: "app" } ]
}
)

To test if the user is created successfully, exit mongo shell and issue a new one

1
2
mongo -u appUser -p appPass --authenticationDatabase admin app
show collections

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
2
3
4
5
db.find()
db.list.insertOne({
something: 'else'
})
db.list.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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const MongoClient = require('mongodb').MongoClient

const url = 'mongodb://appUser:appPass@localhost:27017/app?authSource=admin'
const db = 'app'

const main = async () => {
console.log('start')
const client = await MongoClient.connect(url, { useNewUrlParser: true })
const col = client.db(db).collection('list')
const res = await col.find({}, { limit: 5 }).toArray()
console.log(res)
await client.close()
console.log('end')
}
main()

Note: option authSource is used to specify authenticationDatabase.

References:

  1. MongoDB Manual on authentication.

  2. SO entry on which authentication database to use