Security & Authentication
A default MongoDB installation accepts all connections with no authentication — dangerous for any internet-accessible server. This guide covers enabling authentication, role-based access control, and network security.
Enabling Authentication
/etc/mongod.conf — enable auth
security: authorization: enabled
Create the first admin user (before enabling auth)
use admin
db.createUser({
user: 'admin',
pwd: passwordPrompt(), // prompts securely
roles: [{ role: 'root', db: 'admin' }],
})Authentication Mechanisms
Mechanism | Description | Use Case |
|---|---|---|
SCRAM-SHA-256 | Password-based (default since 4.0) | Most deployments |
X.509 | Certificate-based mutual TLS | Client certificate auth |
LDAP (Enterprise) | Corporate directory integration | Enterprise SSO |
Kerberos (Enterprise) | Ticket-based SSO | Enterprise environments |
Role-Based Access Control (RBAC)
MongoDB RBAC grants permissions through roles. Follow the principle of least privilege — give each user only the permissions their application actually needs.
Built-in Roles
Role | Access | Use Case |
|---|---|---|
read | Read one database | Read-only app user |
readWrite | Read + write one database | Application user |
dbAdmin | Schema management | Developer/DBA |
userAdmin | Manage users in one DB | DBA |
dbOwner | All on one database | Full DB ownership |
readAnyDatabase | Read all databases | Reporting user |
root | Superuser (all) | Admin only — never use for apps |
Creating Users
Create an application user
use myDatabase
db.createUser({
user: 'appUser',
pwd: 'str0ngP@ssword!',
roles: [{ role: 'readWrite', db: 'myDatabase' }],
})Create a read-only reporting user
db.createUser({
user: 'reporter',
pwd: passwordPrompt(),
roles: [{ role: 'read', db: 'myDatabase' }],
})Custom Roles
Custom role with specific privileges
db.createRole({
role: 'orderProcessor',
privileges: [
{
resource: { db: 'myDatabase', collection: 'orders' },
actions: ['find', 'update'],
},
{
resource: { db: 'myDatabase', collection: 'inventory' },
actions: ['find', 'update'],
},
],
roles: [], // no inherited roles
})TLS/SSL Encryption
Enable TLS in mongod.conf
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pemNetwork Security
Bind MongoDB to specific IPs with
net.bindIpin mongod.conf — never leave it as 0.0.0.0 in productionUse a firewall to restrict port 27017 to application servers only
Deploy MongoDB on a private network — never expose it directly to the public internet
Use VPC peering or Private Link for cloud deployments (Atlas supports both)
Atlas Security Features
Encryption at rest — always enabled
In-transit TLS — always enabled
IP access list and VPC peering / Private Link
Unified auditing for compliance
Client-side field-level encryption (queryable encryption)
LDAP integration and SCIM provisioning
Atlas App Services built-in authentication (JWT, Google, Apple, etc.)