iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Security & Auth

MongoDB security in production: authentication, RBAC, network isolation, encryption, and the audit log.

Hardening Mongo

EXAMPLE
// 1. Authentication
// Never run with --auth off in any environment.
// /etc/mongod.conf
security:
  authorization: enabled

// 2. Create users with least privilege
use admin
db.createUser({
  user: 'admin',
  pwd: passwordPrompt(),
  roles: [{ role: 'userAdminAnyDatabase', db: 'admin' }]
});

use myapp
db.createUser({
  user: 'app',
  pwd: passwordPrompt(),
  roles: [{ role: 'readWrite', db: 'myapp' }]
});

// 3. Network isolation
// bindIp only to private interfaces; never 0.0.0.0
// Use VPC peering or PrivateLink on Atlas
net:
  bindIp: 127.0.0.1,10.0.0.5
  port: 27017

// 4. TLS for client connections
// On Atlas this is enforced. Self-hosted:
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongo/cert.pem

// 5. Encryption at rest
// WiredTiger encryption (Enterprise) or platform disk encryption (KMS-backed EBS/Persistent Disk)

// 6. Audit log
auditLog:
  destination: file
  path: /var/log/mongo/audit.json
  format: JSON
  filter: '{ atype: { $in: ["authenticate", "createUser", "dropUser"] } }'

// 7. Field-level encryption (CSFLE / Queryable Encryption)
// Encrypt sensitive fields client-side; the server stores ciphertext.
const client = new MongoClient(uri, {
  autoEncryption: {
    keyVaultNamespace: 'encryption.__keyVault',
    kmsProviders: { aws: { accessKeyId, secretAccessKey } },
  },
});

// 8. Restrict cluster admin
// Reserve clusterAdmin to break-glass users only
// Day-to-day app users get readWrite on a single database

// 9. Backups - encrypted, tested
// Run a restore drill quarterly; an untested backup is hope, not safety

Why it matters

Database security is layered: auth + RBAC + network + TLS + audit + CSFLE for the most sensitive fields. Atlas gives you most of this with one click; self-hosted requires deliberate setup. Test backups - the day you need them is the wrong day to discover they were broken.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Always: TLS, scoped roles, no public open clusters.
// Use env vars for secrets; rotate them.
Try it Yourself »

Discussion

Loading…