MongoDB security: authentication, authorization, and TLS setup
authentication mechanisms, SCRAM, createUser, role-based access control, built-in roles, custom roles, TLS/SSL configuration, IP whitelist, keyfile auth between nodes
Enable authentication before anything else
MongoDB ships with authentication disabled by default. Before exposing any port in a non-development environment, enable authentication by starting mongod with the --auth flag or by adding security.authorization: enabled to your mongod.conf. Always combine auth with TLS to prevent credentials from being transmitted in plaintext over the network.
// Step 1: create admin user while auth is OFF
use admin
db.createUser({
user: 'dbAdmin',
pwd: 'UseAStrongPassword123!',
roles: [{ role: 'userAdminAnyDatabase', db: 'admin' }]
})
// Restart mongod with --auth, then authenticate all future connections
// Step 2: create a scoped application user with minimum permissions
use shopDB
db.createUser({
user: 'shopApp',
pwd: 'AnotherStrongPass456!',
roles: [{ role: 'readWrite', db: 'shopDB' }]
})Key built-in roles and least privilege
read — query only. readWrite — full CRUD plus index creation. dbAdmin — schema and index management. userAdmin — manage users and roles. clusterAdmin — replica sets and sharding operations. Application service accounts should always have readWrite on their specific database and nothing higher. If credentials leak, the blast radius is limited to one database.
// TLS-enabled connection string
'mongodb://shopApp:pass@host:27017/shopDB?tls=true&tlsCAFile=/certs/ca.pem'Beyond user-based access control, always restrict which IP addresses can reach the MongoDB port using firewall rules or MongoDB Atlas IP Access Lists. The MongoDB port (default 27017) should never be exposed to the public internet — even with authentication enabled, an exposed port invites brute-force attacks and vulnerability scanning from automated bots around the clock.
