Enable Authentication on MongoDB

|
Last Updated:
|
|
Enable Authentication on MongoDB

In this guide, you will learn how to enable authentication on MongoDB database. Authentication is one of the access controls which ensures that whoever needs to access any data on the MongoDB database has to verify that they are who they claim they are using their user account passwords.

Learn how to install MongoDB on Linux by following the link below;

How to Install MongoDB on Linux

Enabling Authentication on MongoDB

By default, self hosted MongoDB doesn’t enforce user authentication by default. For example, when you connect to MongoDB from the command line using the mongosh or command mongosh mongodb://127.0.0.1:27017, you will connect with no prompt for authentication.

mongosh

Or

mongosh mongodb://127.0.0.1:27017

This gets you directly onto the default MongoDB database shell prompt.

Current Mongosh Log ID:	6624b6e86d2da8a9e3c934dc
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.4
Using MongoDB:		7.0.8
Using Mongosh:		2.2.4

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-04-21T06:10:47.674+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2024-04-21T06:10:48.114+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

test>

This basically means that, any one with access to the system, can do anything possible to MongoDB databases since there is no restriction implemented.

For example, once can list the databases;

show dbs
admin   40.00 KiB
config  72.00 KiB
local   40.00 KiB

So, how can you enabling authentication?

There are several security features that can be implemented to secure MongoDB deployments. One of these features is the ability to enable MongoDB access control through enforcement of user authentication.

Authentication is the process of validating the identity of a user connecting to a MongoDB.

MongoDB uses various authentication mechanisms such as;

  • Salted Challenge Response Authentication Mechanism (SCRAM) which is the default MongoDB authentication mechanism. It verifies the supplied user credentials against the user’s namepassword and authentication database.
  • x.509 Certificate Authentication, which authenticates clients using x.509 certificates instead of usernames and passwords.
  • And many other mechanisms.

In this guide, we will learn how to enable MongoDB authentication using SCRAM method, which involves the use of usernames and passwords to validate users identity.

Create MongoDB Administrative User

To begin with, connect to a MongoDB instance and create a MongoDB administrative user.

mongosh

If you check from MongoDB shell prompt, no user is created by default;

show users

Or

db.getUsers();

The commands above prints no result.

To create an admin user, switch to default admin MongoDB database.

Listing available databases first;

show dbs

Sample output;

admin   40.00 KiB
config  72.00 KiB
local   40.00 KiB

Next, run the command below from the shell prompt to switch to MongoDB default admin database;

use admin

Once you have switched to admin database, paste the command below on the shell to create MongoDB admin user.

Be sure to replace the username of the administrator as you wish.

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

Press Enter once you have pasted the command call above. You will be prompted to enter your password. If you need to display the password in cleartext, simply replace passwordPrompt() with “your password“.

The command above simply create an admin user with the following roles;

  • roles: This field specifies the roles assigned to the user. Roles define the user’s permissions and privileges within the MongoDB database.
    • { role: “userAdminAnyDatabase”, db: “admin” }: Grants the user administrative privileges (userAdminAnyDatabase) on the admin database. This role allows the user to create and manage users on any database.
    • “readWriteAnyDatabase”: Grants the user read and write access (readWriteAnyDatabase) to any database. This role allows the user to read and write data to any database in the MongoDB instance.

Sample output of creating an admin user on MongoDB;

******{ ok: 1 }

List users again to confirm;

show users
[
  {
    _id: 'admin.kifarunixAdmin',
    userId: UUID('766ca619-b033-4f21-983c-9454b36e3449'),
    user: 'kifarunixAdmin',
    db: 'admin',
    roles: [
      { role: 'readWriteAnyDatabase', db: 'admin' },
      { role: 'userAdminAnyDatabase', db: 'admin' }
    ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]

Once you have created an admin user, exit the database connection;

quit ()

Enable Access Control on MongoDB

MongoDB provides an option, security.authorization, for enabling or disabling role based access control (RBAC).

To enable this option, edit MongoDB configuration file, /etc/mongod.conf, and set the value for this option to enabled.

Open the file for editing;

sudo vim /etc/mongod.conf

Update the line, #security, to look like;

security:
    authorization: enabled

Your config should look like;

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:
security:
    authorization: enabled

#operationProfiling:

Save and exit the file.

Restart MongoDB service;

sudo systemctl restart mongod

Verifying MongoDB Authentication

Next, to verify if authentication works, connect to MongoDB;

mongosh

If you get the error;

Current Mongosh Log ID:	6624bb0d8db6dfae65c934dc
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.4
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

Then MongoDB is not running;

systemctl status mongod
× mongod.service - MongoDB Database Server
     Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Sun 2024-04-21 07:06:38 UTC; 24s ago
   Duration: 35ms
       Docs: https://docs.mongodb.org/manual
    Process: 10918 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=14)
   Main PID: 10918 (code=exited, status=14)
        CPU: 32ms

Apr 21 07:06:38 noble-numbat systemd[1]: Started mongod.service - MongoDB Database Server.
Apr 21 07:06:38 noble-numbat mongod[10918]: {"t":{"$date":"2024-04-21T07:06:38.032Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"main","msg":"Environment variable MONGODB_CON>
Apr 21 07:06:38 noble-numbat systemd[1]: mongod.service: Main process exited, code=exited, status=14/n/a
Apr 21 07:06:38 noble-numbat systemd[1]: mongod.service: Failed with result 'exit-code'.

Check the log file for errors;

sudo grep -i error /var/log/mongodb/mongod.log
{"t":{"$date":"2024-04-21T06:10:47.674+00:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=1447M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],"}}
{"t":{"$date":"2024-04-21T06:10:48.149+00:00"},"s":"I",  "c":"CONTROL",  "id":20712,   "ctx":"LogicalSessionCacheReap","msg":"Sessions collection is not set up; waiting until next sessions reap interval","attr":{"error":"NamespaceNotFound: config.system.sessions does not exist"}}
{"t":{"$date":"2024-04-21T07:06:37.957+00:00"},"s":"I",  "c":"CONTROL",  "id":23377,   "ctx":"SignalHandler","msg":"Received signal","attr":{"signal":15,"error":"Terminated"}}
{"t":{"$date":"2024-04-21T07:06:37.958+00:00"},"s":"W",  "c":"NETWORK",  "id":23022,   "ctx":"listener","msg":"Unable to remove UNIX socket","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}
{"t":{"$date":"2024-04-21T07:06:38.040+00:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}
{"t":{"$date":"2024-04-21T07:09:01.260+00:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}
{"t":{"$date":"2024-04-21T07:14:45.327+00:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}
{"t":{"$date":"2024-04-21T07:21:23.655+00:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}
{"t":{"$date":"2024-04-21T07:30:04.411+00:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}

If you see such error,

"msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}}

The, remove the socket file and restart mongod service;

sudo rm -rf /tmp/mongodb-27017.sock
sudo systemctl restart mongod

Ensure MongoDB is running;

ss -altnp | grep :27
LISTEN 0      4096       127.0.0.1:27017      0.0.0.0:*    users:(("mongod",pid=11780,fd=14))

Then login to the database;

mongosh

Try to list available database users;

show users

You will get such an error that MongoServerError[Unauthorized]: Command usersInfo requires authentication.

To authenticate as a user, switch to admin database;

use admin

Next, run the command below to login as the administrative user created above (Replace the username accordingly);

db.auth("kifarunixAdmin")

Similarly, you can authenticate directly to a specific database from command line;

mongosh -u <username> -p <password> --authenticationDatabase <authDatabase> <connectionString>

Where:

  • <username>: Your MongoDB username.
  • <password>: Your MongoDB password.
  • <authDatabase>: The authentication database where the user credentials are stored.
  • <connectionString>: The connection string for your MongoDB server, including the hostname, port, and database name.

E.g;

mongosh -u kifarunixAdmin -p --authenticationDatabase admin admin

Or

mongosh -u kifarunixAdmin -p --authenticationDatabase admin mongodb://localhost:27017/admin

Enter your password.

Once connected to MongoDB, run the commands as you wish. e.g list available users;

show users
admin> show users
[
  {
    _id: 'admin.kifarunixAdmin',
    userId: UUID('766ca619-b033-4f21-983c-9454b36e3449'),
    user: 'kifarunixAdmin',
    db: 'admin',
    roles: [
      { role: 'readWriteAnyDatabase', db: 'admin' },
      { role: 'userAdminAnyDatabase', db: 'admin' }
    ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]

You can further create databases and respective users and roles.

That simply marks the end of our tutorial on how to enable MongoDB authentication.

Reference

MongoDB Authentication

Other Tutorials

Install and Configure SSSD for OpenLDAP Authentication on Fedora 32/31/30

Configure Squid Proxy OpenLDAP Authentication on pfSense

Configure Offline Authentication via OpenLDAP on MacOS X

Configure OpenLDAP Authentication on MacOS X

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We're passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Photo of author
gen_too
Co-founder of Kifarunix.com, Linux Tips and Tutorials. Linux/Unix admin and author at Kifarunix.com.

Leave a Comment