MongoDB Security and Authentication

A database that stores real user data must be protected from unauthorized access, data leaks, and malicious operations. MongoDB provides a comprehensive set of security features including authentication, authorization, encryption, and network controls. Applying these features correctly protects both the database and the data it holds.

Authentication — Verifying Identity

Authentication is the process of confirming who is trying to connect to the database. MongoDB requires users to provide a username and password before accessing any database resources when authentication is enabled.

Enabling Authentication

On a local MongoDB installation, authentication is disabled by default for convenience during development. For production, it must be enabled by adding the following to the MongoDB configuration file (mongod.conf):

security:
  authorization: enabled

After saving this change, restart the MongoDB service for the setting to take effect.

Creating the First Admin User

Before enabling authentication, an admin user must be created. Without at least one admin, the database becomes inaccessible after authentication is turned on.

use admin

db.createUser({
  user: "adminUser",
  pwd: "SecurePass@2025",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

After this, connect to MongoDB using credentials:

mongosh -u adminUser -p SecurePass@2025 --authenticationDatabase admin

Authorization — Controlling What Users Can Do

Authorization determines what an authenticated user is allowed to do. MongoDB uses a role-based access control (RBAC) system. Each user is assigned one or more roles, and each role grants a specific set of permissions.

Built-In Roles

RolePermissions
readRead-only access to a specific database
readWriteRead and write access to a specific database
dbAdminDatabase administration (create indexes, view stats)
userAdminCreate and manage users for a database
clusterAdminFull cluster management (replication, sharding)
readAnyDatabaseRead access to all databases
readWriteAnyDatabaseRead and write access to all databases
userAdminAnyDatabaseManage users across all databases
dbOwnerFull control of one specific database

Creating a Database-Specific User

use shopDB

db.createUser({
  user: "shopApp",
  pwd: "AppPass@123",
  roles: [{ role: "readWrite", db: "shopDB" }]
})

The user shopApp can read and write to shopDB only. It has no access to any other database.

Creating a Read-Only Reporting User

use shopDB

db.createUser({
  user: "reportUser",
  pwd: "ReportOnly@789",
  roles: [{ role: "read", db: "shopDB" }]
})

This user can query data but cannot insert, update, or delete anything. This is ideal for data analysts or reporting tools that should never modify data.

Managing Users

View All Users in a Database

use shopDB
db.getUsers()

Update a User's Password

db.changeUserPassword("shopApp", "NewSecurePass@456")

Grant Additional Roles to a User

db.grantRolesToUser("shopApp", [{ role: "dbAdmin", db: "shopDB" }])

Revoke a Role from a User

db.revokeRolesFromUser("shopApp", [{ role: "dbAdmin", db: "shopDB" }])

Delete a User

db.dropUser("reportUser")

Network Security

Bind IP Address

By default, MongoDB listens on all network interfaces, which exposes it to the entire network. In production, restrict it to listen only on trusted interfaces by setting the bind IP in mongod.conf:

net:
  bindIp: 127.0.0.1,10.0.0.5

This restricts connections to the local machine (127.0.0.1) and one specific internal IP (10.0.0.5).

Firewall Rules

MongoDB runs on port 27017 by default. Firewall rules should block all public access to this port and allow connections only from specific application server IP addresses.

Encryption

TLS/SSL — Encrypting Data in Transit

Without encryption, data traveling between the application and MongoDB can be intercepted. TLS (Transport Layer Security) encrypts this connection.

To enable TLS in mongod.conf:

net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb.pem
    CAFile: /etc/ssl/ca.pem

The connection string for clients using TLS:

mongodb://shopApp:AppPass@123@localhost:27017/shopDB?tls=true

Encryption at Rest

Encryption at rest protects data stored on disk. If a hard drive is physically stolen, the data remains unreadable without the encryption key. This feature is available in MongoDB Enterprise and through MongoDB Atlas, which encrypts data by default using AES-256 encryption.

MongoDB Atlas Security

MongoDB Atlas provides several security controls through its dashboard without any manual configuration:

  • Network Access — Whitelists specific IP addresses allowed to connect
  • Database Users — Creates and manages user credentials with roles
  • TLS/SSL — Enabled by default on all Atlas clusters
  • Encryption at Rest — Available on M10 and higher tier clusters
  • Audit Logging — Tracks all database operations for compliance
  • Private Endpoints — Allows connecting via a private network without traffic going over the public internet

Audit Logging

Audit logging records all authentication attempts, database operations, and user actions. This is critical in regulated environments where every data access must be traceable.

In mongod.conf (MongoDB Enterprise):

auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json

Security Best Practices Checklist

Best PracticeWhy It Matters
Enable authenticationPrevents unauthorized connections
Use role-based access controlLimits what each user or app can do
Never use the admin user for appsReduces risk if app credentials are leaked
Restrict bind IPPrevents access from unintended networks
Use strong passwordsResists brute-force attacks
Enable TLS/SSLProtects data while it travels over the network
Encrypt data at restProtects physical data if storage is compromised
Rotate passwords regularlyLimits the impact of credential leaks
Enable audit loggingTracks all access for compliance and investigation
Keep MongoDB updatedApplies security patches from each new release

Summary

MongoDB security relies on authentication to verify identity, authorization (RBAC) to control permissions, network restrictions to limit who can connect, and encryption to protect data both in transit and at rest. Built-in roles like read, readWrite, dbAdmin, and userAdmin provide granular access control. TLS/SSL secures the connection channel. MongoDB Atlas simplifies all of these controls through a web dashboard with default encryption enabled. Following security best practices from the beginning — rather than adding them as an afterthought — ensures the database stays protected throughout its lifetime.

Leave a Comment