MongoDB Security
MongoDB security spans authentication, authorization, encryption, and network isolation. A misconfigured instance exposed to the internet is a common breach vector — follow this guide for production-grade security.
Security Architecture Overview
Client → TLS → mongod/mongos → RBAC check → Encrypted storage
↑
Network firewall / VPC
Defense in depth: no single layer is sufficient alone.
Authentication
MongoDB supports multiple authentication mechanisms:
| Mechanism | Use Case |
|---|---|
| SCRAM-SHA-256 | Default username/password |
| x.509 certificates | Machine-to-machine, no passwords |
| LDAP | Enterprise directory integration |
| Kerberos | Windows/AD environments |
| OIDC | Cloud identity providers (Atlas) |
Create Users
use admin
db.createUser({
user: "appUser",
pwd: passwordPrompt(), // prompts securely in mongosh
roles: [
{ role: "readWrite", db: "myapp" }
]
})
Connect with Authentication
mongosh "mongodb://appUser:password@host:27017/myapp?authSource=myapp"
Never use empty passwords or default credentials in production.
Role-Based Access Control (RBAC)
Built-in Roles
| Role | Scope | Permissions |
|---|---|---|
read |
Database | find, listIndexes |
readWrite |
Database | read + insert, update, delete |
dbAdmin |
Database | createIndex, dropCollection |
userAdmin |
Database | createUser, grantRoles |
clusterAdmin |
Cluster | replSetReconfig, sharding admin |
root |
All | Full superuser — avoid for apps |
Principle of Least Privilege
// Application user — only readWrite on one database
db.createUser({
user: "shop_api",
pwd: "...",
roles: [{ role: "readWrite", db: "shop" }]
})
// Read-only analytics user
db.createUser({
user: "analytics",
pwd: "...",
roles: [{ role: "read", db: "shop" }]
})
// Backup user — backup role only
db.createUser({
user: "backup",
pwd: "...",
roles: [
{ role: "backup", db: "admin" },
{ role: "restore", db: "admin" }
]
})
Custom Roles
use shop
db.createRole({
role: "orderProcessor",
privileges: [
{
resource: { db: "shop", collection: "orders" },
actions: ["find", "insert", "update"]
},
{
resource: { db: "shop", collection: "inventory" },
actions: ["find", "update"]
}
],
roles: []
})
db.createUser({
user: "orderWorker",
pwd: "...",
roles: [{ role: "orderProcessor", db: "shop" }]
})
Custom roles restrict access to specific collections and actions.
Enable Authentication
# mongod.conf
security:
authorization: enabled
Create the first admin user before enabling auth, or you lock yourself out.
use admin
db.createUser({
user: "admin",
pwd: "...",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
Encryption In Transit (TLS)
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/mongodb/server.pem
CAFile: /etc/mongodb/ca.pem
Connection string:
mongodb://user:pass@host:27017/myapp?tls=true&authSource=admin
Atlas enforces TLS by default — no configuration needed.
Encryption At Rest
Options:
- WiredTiger encrypted storage engine (Enterprise)
- Cloud provider disk encryption (EBS, Azure Disk Encryption, GCP CMEK)
- Filesystem encryption (LUKS, BitLocker)
Atlas encrypts all data at rest automatically.
# Enterprise — encrypted storage engine
security:
enableEncryption: true
encryptionKeyFile: /etc/mongodb/keyfile
Network Security
Bind to Private IPs Only
net:
bindIp: 10.0.1.5,127.0.0.1
port: 27017
Never expose 0.0.0.0:27017 to the public internet.
Firewall Rules
# Allow only application servers
sudo ufw allow from 10.0.2.0/24 to any port 27017
sudo ufw deny 27017
In cloud environments, use security groups / VPC peering — no public IP on database nodes.
Auditing (Enterprise / Atlas)
Track who did what and when:
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.json
filter: '{ "atype": { "$in": ["authenticate", "authCheck", "createUser", "dropCollection"] } }'
Review audit logs for compliance (SOC 2, HIPAA, PCI-DSS).
Field-Level Encryption
Encrypt specific fields client-side — server never sees plaintext:
const client = new MongoClient(uri, {
autoEncryption: {
keyVaultNamespace: "encryption.__keyVault",
kmsProviders: {
aws: { accessKeyId: "...", secretAccessKey: "..." }
}
}
})
// Insert — SSN encrypted automatically
await collection.insertOne({ name: "Alice", ssn: "123-45-6789" })
Use for PII, PHI, and PCI data where regulations require field-level protection.
Security Checklist
- Authentication enabled with strong passwords
- Application uses least-privilege roles (not
root) - TLS enforced for all connections
- Network bound to private IPs; firewall configured
- No default/empty credentials
- Encryption at rest enabled
- Regular user access review
- Audit logging enabled (Enterprise/Atlas)
- MongoDB version patched and supported
- Backups encrypted and access-controlled
Common Mistakes
- Deploying without authentication — bots scan for open port 27017 within minutes
- Using
rootrole for application connections - Storing credentials in source code instead of secrets manager
- Disabling TLS in production for “performance” — negligible overhead
- Granting
readWriteAnyDatabasewhenreadWriteon one DB suffices - Forgetting to rotate passwords and certificates
Troubleshooting
Authentication failed
# Verify authSource matches where user was created
mongosh "mongodb://user:pass@host:27017/myapp?authSource=admin"
TLS handshake failure
# Test TLS connection
mongosh "mongodb://host:27017" --tls --tlsCAFile ca.pem
User lacks permission
db.runCommand({ connectionStatus: 1, showPrivileges: true })
// Check granted roles and privileges
Production Scenario: Multi-Tenant SaaS
// Tenant-scoped application user
db.createUser({
user: "tenant_app",
pwd: "...",
roles: [{ role: "readWrite", db: "tenant_data" }]
})
// Separate database per tenant OR collection-level isolation with strict queries
// Never share a readWrite user across tenants
Combine RBAC with application-level tenant filtering for defense in depth.
Atlas Security Features
- IP access list (whitelist)
- VPC peering and PrivateLink
- Database auditing
- Encryption at rest and in transit (default)
- Advanced LDAP/OIDC integration
Best Practices
- Treat MongoDB like any production database — never skip auth
- Use secrets managers (AWS Secrets Manager, Vault) for credentials
- Rotate credentials quarterly
- Monitor failed authentication attempts
- Keep MongoDB updated — security patches release regularly
What Comes Next
Replication and sharding build on secure infrastructure — replica set members communicate over authenticated, encrypted channels.