Authentication, authorization & encryption
|
This section documents the current MongoDB 8.x server line as published at the MongoDB Server Manual, which is the reference these pages are written and verified against. No specific patch version is pinned. Some capabilities (Atlas Search, Atlas Vector Search, and parts of encryption and backup) are Atlas-only — they are linked, not documented in depth. This content was generated with the assistance of AI and should be verified against the official manual before being relied on in production, since MongoDB iterates quickly. This section’s bibliography lists the reference material consulted while preparing these pages. |
A default mongod performs no authentication: anyone who can reach the port is a full administrator. Securing
a deployment means turning on access control, giving each client an identity and a minimal set of roles,
encrypting traffic in transit, and — where the data warrants it — encrypting it at rest and in the driver.
Enabling access control
Start mongod with --auth (or security.authorization: enabled in the config file) to require every
connection to authenticate. Before the first user exists, the localhost exception applies: a connection
made from the same machine may create exactly one user, and only in the admin database. Use that one
opening to create a user administrator, after which the exception closes.
# https://www.mongodb.com/docs/manual/tutorial/enable-authentication/
# /etc/mongod.conf
security:
authorization: enabled
net:
bindIp: 127.0.0.1,10.0.0.11
// connected locally, using the localhost exception
use admin
db.createUser({
user: "mainAdmin",
pwd: passwordPrompt(), // never inline the password
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
// from now on, authenticate first
db.auth("mainAdmin", passwordPrompt())
Grant userAdminAnyDatabase first, then use that account to create application users with narrower roles.
root is available for bootstrap but should not be a day-to-day identity.
Authentication mechanisms
Authentication proves who a client is. MongoDB supports several mechanisms; the right one depends on the identity system already in place.
-
SCRAM (
SCRAM-SHA-256, withSCRAM-SHA-1for legacy clients) is the default: salted challenge-response over a username and password stored in theadmin.system.userscollection. -
x.509 certificates authenticate a client by the subject of a TLS client certificate, so there is no password to manage. The certificate’s subject DN becomes the MongoDB username.
-
Enterprise adds external mechanisms: LDAP (
PLAIN) proxy authentication, Kerberos (GSSAPI) for Active Directory / MIT KDC single sign-on, and OIDC (MONGODB-OIDC) for workforce and workload identity from an OpenID Connect provider.
// https://www.mongodb.com/docs/manual/core/authentication/
// create a user that authenticates with an x.509 client certificate
db.getSiblingDB("$external").runCommand({
createUser: "CN=orders-service,OU=apps,O=Example",
roles: [ { role: "readWrite", db: "shop" } ]
})
# connect with a client certificate instead of a password
mongosh --tls \
--tlsCertificateKeyFile /etc/mongo/orders-service.pem \
--tlsCAFile /etc/mongo/ca.pem \
--authenticationDatabase '$external' \
--authenticationMechanism MONGODB-X509 \
"mongodb://mongo.example.internal:27017/shop"
Cluster member authentication
Replica set and sharded cluster members must also authenticate to each other, or any host could join the
set. A small deployment uses a shared keyfile (a base64 secret readable only by the mongod user); a
production deployment uses x.509 member certificates. Enabling either also enables client access control.
# https://www.mongodb.com/docs/manual/tutorial/enforce-keyfile-access-control-in-existing-replica-set/
security:
authorization: enabled
keyFile: /etc/mongo/replica.key
# or, preferred for production:
# net.tls.clusterFile + security.clusterAuthMode: x509
Keyfile provisioning for a replica set is walked through in Replication.
Role-based access control
Authorization decides what an authenticated user may do. MongoDB grants users one or more roles; each
role is a bundle of privileges, and a privilege is a set of actions (such as find, insert,
createIndex) on a resource (a database, a collection, or the whole cluster). Roles can inherit other
roles.
Built-in roles cover the common cases:
-
Per-database:
read,readWrite,dbAdmin,dbOwner,userAdmin. -
Cluster-wide:
clusterMonitor,clusterManager,clusterAdmin,hostManager. -
All-database variants:
readAnyDatabase,readWriteAnyDatabase,dbAdminAnyDatabase,userAdminAnyDatabase. -
Superuser:
root.
When no built-in role fits, define a custom role with exactly the actions needed:
// https://www.mongodb.com/docs/manual/core/authorization/
use shop
db.createRole({
role: "orderProcessor",
privileges: [
{ resource: { db: "shop", collection: "orders" },
actions: [ "find", "update", "insert" ] },
{ resource: { db: "shop", collection: "audit" },
actions: [ "insert" ] }
],
roles: []
})
db.createUser({
user: "orders-app",
pwd: passwordPrompt(),
roles: [ { role: "orderProcessor", db: "shop" } ]
})
// later: adjust an existing user's roles
db.grantRolesToUser("orders-app", [ { role: "read", db: "reporting" } ])
Transport encryption (TLS/SSL)
Without TLS, credentials and documents cross the network in cleartext. Configure mongod and mongos with
a server certificate and a CA file, require TLS for client connections, and use the same settings for
intra-cluster traffic so replication and sharding are encrypted too.
# https://www.mongodb.com/docs/manual/core/security-transport-encryption/
net:
bindIp: 127.0.0.1,10.0.0.11
port: 27017
tls:
mode: requireTLS
certificateKeyFile: /etc/mongo/mongod.pem
CAFile: /etc/mongo/ca.pem
mongosh --tls --tlsCAFile /etc/mongo/ca.pem \
"mongodb://mongo.example.internal:27017/?replicaSet=rs0"
Network hardening goes with it: bind only to the interfaces that need access (bindIp, never 0.0.0.0 on an
untrusted network), keep port 27017 off the public internet, and put the deployment behind a firewall or
private subnet that only application hosts can reach.
Encryption at rest and in the client
Encryption at rest protects the on-disk files if the media is stolen. MongoDB Enterprise provides a native encrypted storage engine, and MongoDB Atlas encrypts storage by default with optional customer-managed keys through a cloud KMS. Because the Atlas KMS wiring is console-driven, this page links it rather than detailing steps: see Encryption at Rest. Disk-level encryption (LUKS, cloud volume encryption) is a valid alternative for Community deployments.
Client-side field level encryption (CSFLE) and Queryable Encryption go further: the driver encrypts
selected fields before they leave the application, using data encryption keys stored in a key vault
collection, each wrapped by a customer master key held in a KMS (AWS KMS, Azure Key Vault, GCP KMS, or a
local key for testing). The mongod server stores and returns only ciphertext for those fields and never
holds the keys. Queryable Encryption additionally allows equality (and, in later versions, range) queries
directly on the encrypted fields.
// https://www.mongodb.com/docs/manual/core/queryable-encryption/
// mongosh sketch: automatic encryption driven by an encrypted-fields schema
const encryptedFieldsMap = {
"shop.customers": {
fields: [
{ path: "ssn", bsonType: "string", queries: { queryType: "equality" } },
{ path: "dob", bsonType: "date" }
]
}
};
const secure = Mongo(
"mongodb://mongo.example.internal:27017/?replicaSet=rs0",
{
autoEncryption: {
keyVaultNamespace: "encryption.__keyVault",
kmsProviders: { /* aws | azure | gcp | local */ },
encryptedFieldsMap
}
}
);
// inserts and equality queries on `ssn` transparently encrypt/decrypt in the driver
secure.getDB("shop").customers.insertOne({ name: "A. Buyer", ssn: "123-45-6789" });
secure.getDB("shop").customers.findOne({ ssn: "123-45-6789" });
Auditing (Enterprise / Atlas) records authentication attempts, authorization failures, and DDL such as
createUser or dropCollection to a file, the syslog, or the console, giving a tamper-evident trail:
see Auditing.
Security checklist
Bring the pieces together, in roughly this order:
-
Enable access control (
--auth) and create a dedicateduserAdmin; remove or lock downroot. -
Give every application its own user with least-privilege roles — prefer custom roles over the broad
*AnyDatabaseroles. -
Choose an authentication mechanism that matches your identity system (SCRAM, x.509, or an Enterprise external mechanism) and authenticate cluster members with a keyfile or x.509.
-
Require TLS for client and intra-cluster traffic; restrict
bindIp, firewall the hosts, and keep27017off the public internet. -
Encrypt sensitive data at rest, and encrypt the most sensitive fields in the client with CSFLE or Queryable Encryption.
-
Enable auditing, disable server-side scripting if unused, and keep the server patched.
The authoritative, continuously updated version is the MongoDB Security Checklist. Operational follow-through — user rotation, log review, and monitoring — is covered in Administration & monitoring.