Skip to main content
MongoDB
CHAPTER 22 Beginner

MongoDB Security | Authentication & Role-Based Access

Updated: May 16, 2026
15 min read

# CHAPTER 22

MongoDB Security Best Practices

1. Introduction

In 2017, tens of thousands of MongoDB servers were hijacked by ransomware groups, who deleted the databases and demanded Bitcoin to restore them. Why did this happen? Because by default, a local MongoDB installation has Authentication turned OFF. Anyone who finds the IP address can connect and drop the database without a password! In this chapter, we will learn how to lock down a self-hosted MongoDB server using Authentication and Role-Based Access Control (RBAC).

*(Note: If you use MongoDB Atlas, these security features are enabled automatically by default).*

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the catastrophic danger of an unauthenticated database.
  • Create a global Database Administrator (Superuser).
  • Enable Authorization in the mongod.conf configuration file.
  • Implement Role-Based Access Control (RBAC).
  • Create a restricted application user following the Principle of Least Privilege.

3. Step 1: Creating the Superuser (Before Locking the Door)

Before we turn the security locks on, we MUST create an Admin user. If we lock the door before making a key, we will be locked out of our own database!

Open mongosh (currently unauthenticated):

javascript
123456789
// Switch to the special administrative database
use admin

// Create the global superuser
db.createUser({
  user: "global_admin",
  pwd: "SuperSecretPassword123!",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

4. Step 2: Enabling Authentication (mongod.conf)

Now that the key exists, we lock the door. We must edit the core MongoDB configuration file (usually located at /etc/mongod.conf on Linux or inside the bin folder on Windows).

Find the security section, uncomment it, and enable authorization:

yaml
12
security:
  authorization: "enabled"

*You MUST restart the MongoDB server service for this to take effect! (e.g., sudo systemctl restart mongod).*

Now, if you type mongosh and try to run show dbs, MongoDB will throw an error. You must authenticate! mongosh -u globaladmin -p --authenticationDatabase admin

5. Step 3: Role-Based Access Control (RBAC)

You should NEVER connect your Node.js or PHP web application to the database using the global
admin superuser account. If a hacker exploits your web code, they gain superuser access and can drop the server.

We must create a restricted user for the web application using RBAC.

The Principle of Least Privilege: A user should only be given the absolute minimum permissions necessary to do their job. Nothing more.

javascript
12345678910111213
// Switch to the specific application database
use ecommerce_db

// Create a restricted user for the web application
db.createUser({
  user: "webapp_user",
  pwd: "WebAppPassword99!",
  roles: [ 
      // This role allows reading and writing data in ecommerce_db ONLY.
      // They CANNOT drop the database, and they CANNOT read the admin database!
      { role: "readWrite", db: "ecommerce_db" } 
  ]
})

6. Read-Only Roles

If you hire a Data Analyst who needs to run Aggregation Pipelines to build reports, you do not want them accidentally running deleteOne(). You assign them the read role.
javascript
123456
db.createUser({
  user: "analyst_sarah",
  pwd: "SarahPassword55",
  roles: [ { role: "read", db: "ecommerce_db" } ]
})
// If Sarah tries to run an updateOne() command, MongoDB will throw a fatal Permission Denied error!

7. Network Security: The Bind IP

Even with passwords, exposing your database to the public internet is dangerous. In mongod.conf, there is a setting called bindIp. By default, it is set to 127.0.0.1 (localhost), meaning only the server itself can talk to the database.

If your Node.js application is on Server A, and MongoDB is on Server B, you must change bindIp to include Server B's private IP address. NEVER set bindIp: 0.0.0.0 unless you have highly advanced enterprise hardware firewalls in place.

8. Mini Project: The Secure Architecture

Let's design the security landscape for a multi-service company.
  1. 1. The DBA (You): Logs in as globalAdmin (Role: root). Full power.
  1. 2. The Main Website (Node.js): Connects as webclient (Role: readWrite on publicdb).
  1. 3. The Accounting Microservice (PHP): Connects as billingservice (Role: readWrite on financedb).
  1. 4. The Audit Team: Connects as auditor (Role: read on financedb).

*(Notice how the Main Website cannot physically access the financedb!)*

9. Common Mistakes

  • Ignoring Security on Localhost: Developers often leave Auth disabled locally because "it's just on my laptop." But if you accidentally run a malicious script you downloaded from NPM, it has full unauthenticated access to wipe your local databases. Always develop with Auth enabled to mirror production environments.

10. Best Practices

  • NoSQL Injection Prevention: Unlike SQL, MongoDB does not use string concatenation for queries, making traditional SQL Injection impossible. However, hackers can pass nested objects in JSON payloads (e.g., {"$ne": null}). Your backend code (PHP/Node.js) MUST sanitize incoming user input and strip out dollar signs ($) before passing data to MongoDB.

11. Exercises

  1. 1. What file must be edited to permanently enable Authorization on a self-hosted MongoDB server?
  1. 2. What built-in role provides permission to execute find(), insertOne(), and updateOne(), but blocks the ability to manage database users?

12. MongoDB Challenges

Write the command to create a user named "backup_service" whose sole purpose is to run mongodump. Give them the built-in backup role on the admin database.
javascript
12345
db.createUser({
  user: "backup_service",
  pwd: "SecureBackupKey!",
  roles: [ { role: "backup", db: "admin" } ]
})

13. MCQ Quiz with Answers

Question 1

What is the fundamental concept behind the "Principle of Least Privilege" in MongoDB RBAC?

Question 2

If a backend API is compromised by a hacker, why is it critical that the API was connected to MongoDB using a readWrite role specific to that application's database, rather than a global administrator role?

14. Interview Questions

  • Q: Explain the mechanical steps required to secure a fresh, unauthenticated installation of MongoDB on a Linux server.
  • Q: Describe how a NoSQL Injection attack differs from a traditional SQL Injection attack, and explain how a backend developer can neutralize it.

15. FAQs

Q: Does MongoDB encrypt data at rest? A: MongoDB Enterprise Advanced and MongoDB Atlas support Transparent Data Encryption (TDE) at rest. MongoDB Community Edition does not, meaning you must rely on Linux Operating System-level disk encryption (like LUKS) to encrypt the physical hard drive.

16. Summary

Security is not an afterthought; it is the foundation. By actively enabling Authentication, utilizing mongod.conf to restrict network access, and aggressively deploying Role-Based Access Control to ensure applications only hold the keys they absolutely need, you transform your NoSQL database from an open target into an impenetrable fortress.

17. Next Chapter Recommendation

Our database is perfectly structured, heavily optimized, backed up, and secured. The database engineering is complete. Now, we must bridge the gap to Software Engineering. In Chapter 23: Connecting MongoDB with PHP, we will write the backend code required to talk to our secure NoSQL server.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·