MongoDB Security
Authentication, authorization, encryption, and security checklist
Skills taught: mongodb.security
Why MongoDB Security Matters
MongoDB's default installation has no authentication enabled. This is intentional for local development but means a publicly exposed MongoDB server is completely open to anyone. Thousands of databases have been compromised because developers forgot to enable authentication before deploying.
Warning: Never deploy MongoDB to a public server without enabling authentication AND restricting network access. An unauthenticated MongoDB on a public IP can be found by port scanners within minutes and ransomed within hours.
Authentication — Who Are You?
// Connect to mongosh as admin first
// (locally without auth enabled yet)
// Step 1: Create the admin user FIRST (before enabling auth)
use admin
db.createUser({
user: 'admin',
pwd: 'UseAStrongPasswordHere!2026',
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' },
{ role: 'clusterAdmin', db: 'admin' }
]
});
// Step 2: Create a least-privilege application user
use myapp
db.createUser({
user: 'appuser',
pwd: 'AnotherStrongPassword2026!',
roles: [
{ role: 'readWrite', db: 'myapp' } // only readWrite on myapp — nothing else!
]
});
// Step 3: Create a read-only reporting user
db.createUser({
user: 'reporter',
pwd: 'ReportingPassword2026!',
roles: [
{ role: 'read', db: 'myapp' } // read-only — cannot insert/update/delete
]
});
Enabling Authentication in mongod.conf
# /etc/mongod.conf — MongoDB server configuration
security:
authorization: enabled # Require authentication for all connections
net:
port: 27017
bindIp: 127.0.0.1 # ONLY accept local connections!
# bindIp: 127.0.0.1,10.0.0.5 # for specific IPs
# bindIp: 0.0.0.0 # NEVER do this in production without firewall!
tls:
mode: requireTLS # Require TLS for all connections
certificateKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem
storage:
dbPath: /var/lib/mongodb
operationProfiling:
slowOpThresholdMs: 100 # Log queries slower than 100ms
mode: slowOp
Role-Based Access Control (RBAC)
MongoDB uses RBAC — each user is assigned roles that grant specific privileges. Follow the principle of least privilege: give each user only the permissions they actually need.
// Built-in roles (from least to most privileged)
// Database-level roles:
// 'read' — find() and aggregate on the specified database
// 'readWrite' — read + insert, update, delete, createCollection
// 'dbAdmin' — manage indexes, explain, rename collections
// 'userAdmin' — create/modify users (for the specified database only)
// Cluster-level roles:
// 'clusterMonitor' — read-only cluster stats
// 'clusterAdmin' — full cluster management (sharding, replication)
// All-database roles (applied to 'admin' db):
// 'readAnyDatabase', 'readWriteAnyDatabase', 'userAdminAnyDatabase'
// Create a custom role with fine-grained permissions
use admin
db.createRole({
role: 'analyticsReader',
privileges: [
{
resource: { db: 'myapp', collection: 'orders' },
actions: ['find', 'aggregate'] // only these two actions
}
],
roles: [] // no inherited roles
});
// Assign the custom role
db.grantRolesToUser('analyst_user', [
{ role: 'analyticsReader', db: 'admin' }
]);
Connecting Securely from Your App
// Store credentials in environment variables — NEVER hardcode
const uri = process.env.MONGODB_URI;
// MONGODB_URI=mongodb://appuser:password@host:27017/myapp?authSource=myapp
// Connection options for production
const client = new MongoClient(uri, {
tls: true,
tlsCAFile: '/path/to/ca.pem', // verify server certificate
serverSelectionTimeoutMS: 5000, // fail fast if no server available
socketTimeoutMS: 45000,
// Connection pool settings for production
maxPoolSize: 50, // max concurrent connections
minPoolSize: 5, // keep 5 connections warm
maxIdleTimeMS: 30000, // close idle connections after 30s
});
// Atlas connection string already includes TLS by default
const atlasUri = process.env.ATLAS_URI;
// mongodb+srv://appuser:password@cluster.mongodb.net/myapp?w=majority
Security Checklist for Production
- Enable authentication — set security.authorization: enabled in mongod.conf
- Create a strong admin password — use a password manager, never a dictionary word
- Create least-privilege app users — app user gets readWrite on its database only, nothing else
- Enable TLS — set net.tls.mode: requireTLS and provide a valid certificate
- Restrict network access — bind MongoDB to internal IP only (not 0.0.0.0), use a firewall to block port 27017 from the internet
- Never store credentials in code — use environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault)
- Enable audit logging (Enterprise/Atlas) — log all authentication attempts and admin operations
- Keep MongoDB updated — security patches are released regularly, check for updates
Tip: MongoDB Atlas handles most of this automatically: TLS is always on, authentication is required, and you manage users through the Atlas UI or API. For self-hosted MongoDB, you must configure every item on the security checklist manually.
Frequently Asked Questions
How do I encrypt data at rest in MongoDB?
MongoDB Enterprise and Atlas provide Encrypted Storage Engine (AES-256-CBC). For MongoDB Community Edition, use Linux full-disk encryption (LUKS/dm-crypt) or cloud provider disk encryption (AWS EBS encryption). For field-level encryption of specific sensitive fields, MongoDB 4.2+ provides Client-Side Field Level Encryption (CSFLE) in all editions.
My MongoDB is behind a VPN — do I still need authentication?
Yes. Defense in depth means multiple security layers. If the VPN is ever breached or a machine inside the VPN is compromised, authentication is your last line of defense. Always enable authentication even on internal networks.
How do I rotate database passwords without downtime?
Create the new user, update your app's connection string to use the new credentials (rolling deploy), then drop the old user. MongoDB Atlas provides a built-in secret rotation feature. For self-managed deployments, use an application-level credential rotation process with a brief period where both old and new credentials work.