Why Authentication Matters
Authentication is how MongoDB verifies who you are. Without it, anyone could connect to your database and do whatever they want. That's a security nightmare.
Think of authentication like showing your ID at a secure building. The guard checks your credentials before letting you in. MongoDB does the same thing with usernames and passwords.
Authentication should be the first thing you set up when deploying MongoDB. Don't wait until later or skip it because "it's just a development server." Even dev servers have valuable data.
Authentication Mechanisms
MongoDB supports several authentication mechanisms. The most common are SCRAM, x.509 certificates, and LDAP. Each has its own use cases and security characteristics.
SCRAM (Salted Challenge Response Authentication Mechanism) is the default and recommended for most deployments. It's secure, well-tested, and doesn't require special infrastructure.
x.509 certificate authentication is great for server-to-server communication and automated systems. LDAP integrates with your existing directory services like Active Directory.
mongod --auth --port 27017
mongosh --authenticationDatabase admin -u admin -p
mongosh --ssl --sslCAFile /path/to/ca.pem \
--sslPEMKeyFile /path/to/client.pem
Creating Users
You create users in the admin database with specific roles that determine what they can do. Each user has a username, password, and a set of roles.
MongoDB has built-in roles like read, readWrite, dbAdmin, and root. You can also create custom roles for fine-grained access control.
Always follow the principle of least privilege. Give users only the permissions they need, nothing more. A reporting app doesn't need write access to your database.
use admin
db.createUser({
user: "appUser",
pwd: "securePassword123",
roles: [
{ role: "readWrite", db: "myApp" },
{ role: "read", db: "analytics" }
]
})
db.createUser({
user: "backupUser",
pwd: "backupSecure456",
roles: [
{ role: "backup", db: "admin" }
]
})
SCRAM Authentication
SCRAM is MongoDB's default authentication method. It uses a challenge-response mechanism, so your password is never sent over the network in plain text.
SCRAM-SHA-256 is the current standard. It's more secure than the older SCRAM-SHA-1. Always use SHA-256 unless you have legacy clients that don't support it.
MongoDB stores user credentials using salted hashes. Even if someone accesses the database files, they can't recover the original passwords.
use admin
db.createUser({
user: "dbAdmin",
pwd: "adminPass789",
mechanisms: ["SCRAM-SHA-256"],
roles: [
{ role: "dbAdmin", db: "production" }
]
})
db.getUsers({ showCredentials: false })
db.auth("dbAdmin", "adminPass789")