(Last Updated On: September 12, 2018)

I know many guys are used to running MongoDB without authentication. If you try a Lynis or Nessus security audit, you’ll likely get a warning for “No MongoDB authorization“. Let’s cover how you can set authentication for a user/database in MongoDB.

You need a running MongoDB to use this guide, use any of below articles to install MongoDB server:

How to Install MongoDB 4 on CentOS 7

How to install Latest MongoDB on Ubuntu 18.04 / Ubuntu 16.04

When mongod service is running, connect to it using the mongocommand line tool

# mongo --port 27017

Then create the user account with “root” role to be the database admin.

> use testdb;
switched to db testdb
> db.createUser(
  {
    user: "dbadmin",
    pwd: "StrongPassword",
    roles: [ { role: "root", db: "admin" } ]
  }
)
> exit
bye

Open the file /etc/mongod.conf and enable authentication

security:
  authorization: enabled

Restart MongoDB

sudo systemctl restart mongod

Test by connecting to testdb as dbadmin user.

mongo --port 27017 -u "dbadmin" -p --authenticationDatabase "testdb"

When asked for the password, enter the password you had set.

MongoDB shell version v4.0.2
Enter password: 
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.0.2
Server has startup warnings: 
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>

You now have a working MongoDB authentication for a user to access a specific database.