Security and Authentication
Securing a MongoDB deployment involves several layers: authenticating who can connect, authorizing what they can do, encrypting data in transit and at rest, and hardening network access. This lesson covers all four.
1. Enabling Authentication
# mongod.conf
security:
authorization: enabled
// Create the first admin user before enabling auth
use admin
db.createUser({
user: "adminUser",
pwd: "SecureP@ssw0rd",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
2. Role-Based Access Control (RBAC)
| Role | Scope |
|---|---|
read / readWrite | Single database |
dbAdmin | Schema and index management |
clusterAdmin | Cluster-wide administration |
readAnyDatabase | Read access across all databases |
db.createUser({
user: "reportViewer",
pwd: "ReportPass123",
roles: [ { role: "read", db: "analyticsDB" } ]
})
3. Custom Roles
db.createRole({
role: "orderManager",
privileges: [
{ resource: { db: "ecommerceDB", collection: "orders" }, actions: ["find", "update", "insert"] }
],
roles: []
})
4. TLS/SSL Encryption in Transit
mongod --tlsMode requireTLS --tlsCertificateKeyFile /etc/ssl/mongodb.pem
TLS ensures data traveling between clients and the server is encrypted, preventing eavesdropping and man-in-the-middle attacks.
5. Encryption at Rest
MongoDB Enterprise and Atlas support encryption at rest, protecting data stored on disk using AES-256 encryption, with keys managed via a local keyfile or an external KMIP-compliant key manager.
Common Issue: Leaving
bindIp set to 0.0.0.0 without a firewall exposes your database to the open internet. Always restrict network access explicitly.
6. Security Checklist
- ✅ Enable authorization on every deployment
- ✅ Apply least-privilege roles per application/user
- ✅ Create custom roles for fine-grained permissions
- ✅ Enforce TLS/SSL for all connections
- ✅ Enable encryption at rest for sensitive data
- ✅ Restrict network access via firewalls/IP allowlists
Key Takeaway: MongoDB security is layered — authentication, authorization, network hardening, and encryption all need to be configured together. No single setting makes a deployment "secure."
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.