Authentication with MongoDB

Configure MongoDB Authentication and Authorization

Updated: 03 September 2023

Configuration File

The Docs

The Configuration File for a MongoDB Instance has all the options that the command line startup contains, use this for storing your configuration in a single location - makes retaining a configuration over multiple environments much easier

The file is located as follows:

OSLocation
Linux/etc/mongod.conf
Windows<install directory>/bin/mongod.cfg
macOS/usr/local/etc/mongod.conf

And the default file looks soomething like this:

mongod.conf

1
# mongod.conf
2
3
# for documentation of all options, see:
4
# http://docs.mongodb.org/manual/reference/configuration-options/
5
6
# Where and how to store data.
7
storage:
8
dbPath: C:\Program Files\MongoDB\Server\4.0\data
9
journal:
10
enabled: true
11
# engine:
12
# mmapv1:
13
# wiredTiger:
14
15
# where to write logging data.
16
systemLog:
17
destination: file
18
logAppend: true
19
path: C:\Program Files\MongoDB\Server\4.0\log\mongod.log
20
21
# network interfaces
22
net:
23
port: 27017
24
bindIp: 127.0.0.1
25
#processManagement:
26
27
#security:
28
29
#operationProfiling:
30
31
#replication:
32
33
#sharding:

Securing an Instance

The Docs

To secure an instance there are a few steps we should take such as:

  1. Enabling Access Control
  2. Enforcing Authentication
  3. Configuring Role-Based access
  4. Encrypt Communication (SSL/TLS)
  5. Encrypt Data
  6. Limit Network Exposure
  7. Audit System Activity
  8. Run Mongo with Secure Enabled
  9. (Misc Compliance Related things)

1. Enable Access Control

The Docs

Enabling a User Admin

To Enable access-control on an instance you will need to first:

  1. Log into the existing instance using the mongo shell
  2. Create a User Admin using the following:
1
use admin
2
db.createUser(
3
{
4
user: "myUserAdmin",
5
pwd: passwordPrompt(), // or cleartext password
6
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
7
}
8
)

At this point you may also want to give your admin root access, you can do this with the following:

1
use admin
2
db.grantRolesToUser("myUserAdmin", [{ role: "root", db: "admin" }])

If you get a passwordPrompt is not defined error then just use the plaintext password

  1. Shut down the instance:
1
db.adminCommand({ shutdown: 1 })
  1. Add the following to the mongod.conf file:
1
security:
2
authorization: enabled

Setting the above config is the same as running mongod --auth when starting up

  1. Restart the instance with the mongod command

If we try to use the DB now and are not authenticated we will get a db command requires autentication error

Note that if you do not restart the database authentication will not be enforced

Creating First User on Localhost

Docs on the Localhost Exception

If a database is started with the --auth param or the security.authorization=enabled, and the first login is done from localhost you will be allowed to create the initial user

Users and Roles

Docs on User Roles

  1. Open a new mongo shell and log in using the user admin credentials we created above:
Terminal window
1
mongo <hostname> --authenticationDatabase "admin" -u "myUserAdmin" -p

And then enter the password on the prompt

  1. We can create a user with some readWrite and read permissions using db.createUser():

Select the DB to create the user (we’ll use admin, but this can be another database):

1
use admin

If you use another database above then the database

Create the User on the DB:

1
db.createUser({
2
user: 'myTester',
3
pwd: 'password', // or cleartext password
4
roles: [
5
{ role: 'readWrite', db: 'dbTest' },
6
{ role: 'read', db: 'dbOtherData' },
7
],
8
})

The created user will then be created on the admin database and will have access to the dbTest and dbOtherData databases

Using the User

From the Mongo Shell

You can now exit the mongo shell and re-login with your new username and password:

Terminal window
1
mongo <hostname> --authenticationDatabase "admin" -u "myTester" -p

Or alternatively, from a currently open instance:

Terminal window
1
mongo <hostname>

You can then authenticate with:

Terminal window
1
use admin
2
db.auth("username", "password")

Thereafter, you should be able to execute queries with the limitations of the roles defined above

If trying to do something that was not allowed for your user you will see an authorization error

From an Application

An example Node.js application that makes use of the above user will look like the following:

1
const { MongoClient } = require('mongodb')
2
const readline = require('readline')
3
4
const dbName = 'dbTest'
5
6
/// Note that our ConnectionString contains the Auth Source
7
const url = `mongodb://myTester:password@localhost:37200/?authSource=admin`
8
9
const rl = readline.createInterface({
10
input: process.stdin,
11
output: process.stdout,
12
})
13
14
// init database
15
MongoClient.connect(url, (err, db) => {
16
if (err) throw err
17
18
console.log('DB Connected')
19
app(db)
20
})
21
22
const app = (db) => {
23
rl.question('Please enter a name to add to the DB ', (name, err) => {
24
if (err) throw err
25
db.db(dbName)
26
.collection('people')
27
.insertOne({ name }, (err, res) => {
28
if (err) throw err
29
30
console.log(res)
31
rl.close()
32
})
33
})
34
35
rl.on('close', () => {
36
console.log('Database Closed')
37
db.close()
38
console.log('Application Closed')
39
process.exit(0)
40
})
41
}

The connection string we use in the above is important, and contains the following pieces of information:

  1. The Database User’s Username
  2. The Database User’s Password
  3. The name of the database to authenticate against

If we want to, we can also define the database we’re using to authenticate with in the connection string like so:

1
mongodb://myTester:password@localhost:37200/admin`

Personally I don’t like this because it implies that we’re using the admin db as the parameter after the / is the database we want to use. The authSource method is clearer in my opinion

Connection strings like the following will not work now that authentication is enabled:

1
mongodb://myTester:incorrectpassword@localhost:37200/?authSource=admin
2
mongodb://localhost:37200/?authSource=admin
3
mongodb://localhost:37200/?authSource=nonExistentDB