Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 70 ยท Security

Authentication and Role-Based Access

Secure MongoDB with users, SCRAM authentication and roles: enable access control, grant least privilege, build custom roles and see how x.509 and LDAP fit in.

A MongoDB server started with default settings and no access control will let any client that can reach its port read and write every database. That is fine on a laptop and a disaster on a network. Securing it takes two separate steps, and it helps to keep them apart in your head. Authentication answers "who are you?" by checking a credential. Authorization answers "what may you do?" by looking up the roles that identity has been granted. MongoDB implements authorization as role-based access control (RBAC): users hold roles, and roles hold privileges.

This lesson walks through enabling access control, creating users, choosing built-in roles, writing custom roles and the idea of least privilege. Everything that talks to a server is shown in read-only blocks, because the site cannot run MongoDB. Two runnable stand-ins at the end model the logic of roles and privileges in plain JavaScript so you can test your role design; they are not MongoDB's security code. Securing the network and disk is covered next in Securing a Deployment.

Two questions

Authentication Who is this client?
Authorization What may this client do?

Authentication proves identity. Roles decide the rest.

1 / 2

Turn on access control

Authentication is off by default. You enable it with the security.authorization setting in mongod.conf, or the --auth command-line flag.

YAML
# mongod.conf
security:
  authorization: enabled
net:
  bindIp: 127.0.0.1

Once enabled, connections without credentials can still open a socket, but almost every command fails with an "requires authentication" error. Managed services such as Atlas have access control on from the start.

A fresh self-hosted server has no users, so you need a way in. MongoDB provides a localhost exception: until the first user is created, a connection from the same machine may create that first user. Make it an administrator who can manage users, and nothing else:

JavaScript
use admin
db.createUser({
  user: "siteAdmin",
  pwd: passwordPrompt(),            // asks interactively, keeps it out of history
  roles: [ { role: "userAdmin", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" } ]
})

Use passwordPrompt() in mongosh rather than a literal password so the secret does not land in your shell history or logs. After this first user exists, the localhost exception ends and everything needs credentials.

Users and where they live

A user is defined in one database, called its authentication database (for example admin or shop). The user's name and that database together identify the account, so app in shop and app in admin are different users. When you connect, you tell the server where to look with the authSource option:

TEXT
mongodb://reportUser:[email protected]:27017/shop?authSource=admin

A very common mistake is creating a user in the shop database and then connecting with authSource=admin (or the reverse). The server answers "Authentication failed", which looks like a wrong password but is really the wrong database. Special characters in a password must be percent-encoded in the URI.

SCRAM, the default mechanism

For password users, MongoDB's default mechanism is SCRAM (Salted Challenge Response Authentication Mechanism). The client and server prove to each other that they know the password without sending the password across the network; the server stores only salted, iterated hashes of it. Two variants exist: SCRAM-SHA-1 and SCRAM-SHA-256, and SHA-256 is preferred for new users. SCRAM protects the password during login but does not encrypt the traffic that follows, so you also want TLS, which is part of the next lesson.

Other mechanisms exist for specific environments:

  • x.509 certificates. A client presents a TLS certificate, and the certificate's subject becomes the username. This suits service-to-service connections where handing out passwords is awkward, and it is also how cluster members can authenticate to each other.
  • LDAP and Kerberos. In MongoDB Enterprise and Atlas, users can be authenticated by a corporate directory instead of the database. Roles can be mapped from directory groups. This is mostly an administrator decision, so treat it as an overview: know it exists when your company already runs a directory.
  • Cloud identity. Atlas also supports federated identities and workload identities for passwordless access; check the current Atlas documentation for what is available.

Built-in roles

You almost never write privileges from scratch, because MongoDB ships with built-in roles. These are the ones to know first:

Role What it allows
read Read all non-system collections of one database
readWrite read, plus insert, update and delete in that database
dbAdmin Administrative tasks such as indexes and statistics, not data reads
userAdmin Create users and roles in that database
readAnyDatabase, readWriteAnyDatabase The same, across all databases (granted in admin)
clusterMonitor Read monitoring data for the cluster
backup, restore Back up or restore data
root Superuser: nearly everything

A typical split gives your web application readWrite on its own database and a reporting job read on the same database:

JavaScript
use shop
db.createUser({
  user: "shopApp",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "shop" } ]
})

db.createUser({
  user: "reports",
  pwd: passwordPrompt(),
  roles: [ { role: "read", db: "shop" } ]
})

Granting root to an application because "it makes errors go away" is the most common security shortcut. Resist it: if that application is ever compromised, the attacker holds the whole deployment.

Role families in more detail

Beyond the roles above, built-in roles fall into families. Each family is granted on a specific database unless it ends in AnyDatabase or lives only in admin.

Family Roles What they are for
Database user read, readWrite Application access to the data of one database
Database administration dbAdmin, dbOwner, userAdmin Indexes, stats and schema validation (dbAdmin); everything in one database (dbOwner = readWrite + dbAdmin + userAdmin); managing users and roles (userAdmin)
Cluster administration clusterAdmin, clusterManager, clusterMonitor, hostManager Managing replica sets and shards (clusterManager), read-only monitoring (clusterMonitor), restarts and server operations (hostManager); clusterAdmin is the union of these and dropDatabase
Backup and restore backup, restore Run mongodump and file-system snapshots; run mongorestore. Atlas has its own backup roles.
All-database roles readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, dbAdminAnyDatabase Same powers on every database, only granted in admin
Superuser root Everything, including all of the above

clusterAdmin is the strongest cluster role, so give it only to the people who run the deployment. A monitoring agent needs clusterMonitor and nothing else.

Creating a user step by step

A first administrator is created while the server is reachable only locally (the localhost exception), then access control is enforced:

JavaScript
use admin
db.createUser({
  user: "adminUser",
  pwd: passwordPrompt(),                      // prompts instead of putting the password in history
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

After restarting mongod with security.authorization: enabled, connect and authenticate, then create the application user in its own database:

Terminal
mongosh "mongodb://localhost:27017" -u adminUser --authenticationDatabase admin
JavaScript
use shop
db.createUser({
  user: "shopApp",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "shop" } ],
  authenticationRestrictions: [ { clientSource: ["10.0.1.0/24"], serverAddress: ["10.0.1.5"] } ],
  mechanisms: ["SCRAM-SHA-256"]
})

authenticationRestrictions limits where the user may connect from: clientSource lists allowed client IP addresses or CIDR ranges, and serverAddress the server addresses the client may connect to, so a leaked password is useless from elsewhere. mechanisms restricts the SCRAM variants. Related options include customData (free-form notes), passwordDigestor (older option choosing whether the server or the client hashes the password; leave it at "server") and digestPassword. Check the result with db.getUser("shopApp"), and test the login with db.auth("shopApp", passwordPrompt()).

Least privilege and custom roles

The principle of least privilege says every account gets only the access it needs for its job and nothing more. Built-in roles are coarse, so when they are too generous you define a custom role: a list of privileges, each pairing a resource (a database, a collection, or both) with the actions allowed on it.

JavaScript
use shop
db.createRole({
  role: "orderClerk",
  privileges: [
    { resource: { db: "shop", collection: "orders" },    actions: [ "find", "insert", "update" ] },
    { resource: { db: "shop", collection: "products" },  actions: [ "find" ] }
  ],
  roles: []        // can also inherit other roles
})

db.createUser({
  user: "clerk1",
  pwd: passwordPrompt(),
  roles: [ "orderClerk" ]
})

Notice that the clerk can find, insert and update orders but cannot remove them, and can only read products. Roles can inherit from other roles through the roles array, which lets you build layers: a base role for read access and a stronger one that adds writes. Review roles with db.getRole("orderClerk", { showPrivileges: true }) and users with db.getUser("clerk1"), and change them later with grantRolesToUser, revokeRolesFromUser and updateUser.

Some practical habits keep a deployment tidy. Create one user per application or service, never a shared login, so you can rotate or revoke one without breaking the rest. Keep application users out of the admin database unless they truly need cluster-wide access. Store passwords in a secrets manager or environment-injected secrets, not in source control. And revisit grants when an application's needs change: privileges tend to grow and rarely shrink.

Modelling roles in a stand-in

You cannot create real users here, but you can test your thinking. The first stand-in models privileges as { db, collection, actions } entries and checks whether a user's roles allow an action. It includes role inheritance, just like the roles: [] array above.

JS Checking privileges for a role design

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The unknown user ghost is denied everything: with no roles there are no privileges, which is the safe default. Real MongoDB reports an error rather than a quiet denied, but the allow/deny logic is the same.

The second stand-in is an audit of a set of accounts: it flags the patterns that most often cause incidents (a superuser role on an application account, an overly broad AnyDatabase role, a shared account).

JS Auditing accounts for risky grants

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real deployments can run a similar review by listing users with db.getUsers() in each database and by checking db.runCommand({ usersInfo: 1, showPrivileges: true }), then comparing the result against what each service actually needs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between authentication and authorization?

    Authentication verifies identity with a credential. Authorization then uses the user's roles to decide which actions are allowed.
  2. 2. You created a user in the shop database, but logging in fails with 'Authentication failed' while using authSource=admin. Why?

    A user belongs to the database it was created in. authSource must name that database or the server will not find the account.
  3. 3. Which grant best follows the principle of least privilege for a reporting tool that only reads the shop database?

    read on the single database it needs gives the tool exactly the access required, and nothing else.
  4. 4. What does SCRAM avoid sending over the network during login?

    SCRAM is a challenge-response exchange: both sides prove knowledge of the password without transmitting it. It does not encrypt later traffic, which is why TLS is also needed.

Summary

  • Access control is off by default on self-hosted servers: enable security.authorization and create an administrator through the localhost exception.
  • Authentication proves identity (SCRAM by default, x.509 for certificates, LDAP/Kerberos in Enterprise and Atlas); authorization uses roles.
  • A user belongs to one database; connect with the matching authSource.
  • Built-in roles (read, readWrite, dbAdmin, userAdmin, root, ...) cover common cases; custom roles pair resources with actions.
  • Follow least privilege: one account per service, narrow roles, no root for applications, secrets kept out of code.
  • SCRAM protects the password, not the traffic: add TLS.

Continue with the network, encryption and auditing side in Securing a Deployment.