skip to content

Access & Secrecy

Who may connect to MongoDB, what each user may do, and which fields the server itself never reads: authentication mechanisms, roles and client-side encryption. Common in platform loops.

part ofMongoDBread it →
on this pageshow

explore

questions

18

In MongoDB, what is a user's authentication database, and what does the `authSource` connection option tell the client?

level: juniorimportance: must knowfreq 48%

answer

  1. a user's identity has two parts
  2. where createUser was run
  3. same name, different database
  4. option first, then path, then admin

basics

~20 s

A MongoDB user is identified by its name plus the database it was created in, called its authentication database. The authSource option names that database at login; without it a client uses the connection string's database, then admin.

solid answer

~40 s

A user's authentication database is the database where it was created with `db.createUser`, and its name plus that database is the user's identity, so `svc` in `orders` and `svc` in `billing` are two separate users. It does not limit what the user can reach, because roles can grant access on other databases, and it is not where the record physically sits: user documents live in `system.users` in the `admin` database, with a `db` field. At login the client must send its credentials to that same database, and `authSource` names it. The order is `authSource`, then the database in the connection string's path, then `admin`. Mechanisms whose credentials live outside MongoDB, such as X.509, Kerberos and LDAP, use the `$external` database instead.

code

javascript · 8 lines
javascript
use orders
db.createUser({
  user: "svc",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "orders" } ]
})

db.getSiblingDB("orders").getUser("svc")

go deeper

for a junior

Recall that a user is a name plus a database, and that the client must log in against that database. Know the order: authSource, then the path in the connection string, then admin.

for a middle

Explain that the authentication database does not cap privileges and is not where the record is stored, and predict from a given connection string which database the login goes to.

for a senior

Treat a generic login failure as a question about which database received the login before you question the password, and know that a connection string's path quietly decides this.

for a principal

Decide where users live as a team convention, such as all in admin or one per application database, because that choice sets how connection strings are templated and audited.

## What an authentication database is In MongoDB, **authentication** means proving who a client is, and a **user** is the record that proof is checked against. Every user is created inside some database, and that database becomes its **authentication database**. You choose it simply by where you run the command: after `use orders`, `db.createUser(...)` makes a user whose authentication database is `orders`. The **name and the authentication database together are the identity**. The manual is explicit that two users with the same name in different databases are two separate users. Each has its own password and its own roles, and changing one does not touch the other. If you want one person or service to work on several databases, you create a single user and give it a role on each database, rather than creating the same name repeatedly. ## What it does not mean The term is easy to over-read. Four things it is not: - **It is not a limit on access.** A user created in `orders` can hold `readWrite` on `billing`. The manual says a user's privileges are not limited to the authentication database and can span several. - **It is not where the record is stored.** All user documents live in the `system.users` collection of the `admin` database. On a sharded cluster, that means the `admin` database on the config servers. The document's `db` field records the authentication database, and its `_id` has the form `<db>.<username>`. You manage these with the user management commands and never edit the collection directly. - **It is not the database the application works in.** The two often match by habit, but nothing requires it. Many teams keep all users in `admin`, and those users work in other databases. - **It does not grant anything by itself.** Being created in `admin` makes nobody an administrator. A user has only the roles it was given. ## How the client decides where to log in The driver authentication specification calls this database the credential's **source**: it is the database to which the authentication commands are sent. For the password mechanisms, a client settles it in this order: 1. The `authSource` option, if it is set. With a `mongodb+srv` address it can also arrive in a DNS TXT record, and an option in the connection string overrides that record. 2. Otherwise, the database in the connection string's path, which the manual calls `defaultauthdb`. 3. Otherwise, `admin`. | Connection string | Authentication database for `svc` | |---|---| | `mongodb://svc:pw@db1:27017/orders` | `orders` | | `mongodb://svc:pw@db1:27017/orders?authSource=admin` | `admin` | | `mongodb://svc:pw@db1:27017/` | `admin` | The trap in that first row is that the path looks like a statement about where the application works, yet it also decides where the login goes. In `mongosh` the path sets the default database as well. Drivers may treat that part differently, so do not assume a driver's working database and its login database are linked. Picking a database in driver code happens after the credential is fixed, so it does not move the login. In `mongosh` you can also name the database with `--authenticationDatabase`, or switch with `use` and then call `db.auth()`, which authenticates against the database you switched to. ## The `$external` database Some users have no password stored in MongoDB because something else proves who they are. Those users log in against a special database called `$external`: - **X.509** certificate users, where the certificate subject is the username. - **Kerberos** users, using the `GSSAPI` mechanism. - **LDAP proxy** users, using the `PLAIN` mechanism. - **OIDC** users, using `MONGODB-OIDC`. The specification fixes the source at `$external` for X.509, Kerberos and OIDC. For those, you normally do not choose an authentication database at all. ## Small rules worth remembering - You cannot create users in the `local` database. - The `authSource` option alone is not a request to authenticate. The specification says that without other credential data it must not be read as one, and the manual adds that it is ignored when no username is given. - The first user on a locked-down deployment must be able to create other users, which is a matter of roles rather than of authentication. ## Why interviewers ask This is a screening question because it explains the most common MongoDB login failure: a correct username and password sent to the wrong database. A candidate who says that a user belongs to a database, and that the client has to be told which one, can already reason about that failure.

  • How do you give one MongoDB user access to several databases?
    Create the user once and give it a role per database, for example `readWrite` on `orders` and `read` on `billing`. Creating the same name in each database instead gives you several unrelated users, each with its own password to rotate. The authentication database then only says where that one user logs in.
  • Does a user created in `admin` have administrator rights in MongoDB?
    No. `admin` is only that user's authentication database, and it is also the fallback a client uses when neither `authSource` nor a path is given. The user's rights come entirely from its roles, so a user in `admin` holding only `read` on `orders` can do no more than that.
  • Does setting `authSource` in a MongoDB connection string make the client authenticate?
    Not by itself. The driver authentication specification says `authSource` without other credential data must not be read as a request to authenticate, and the manual adds that it is ignored when no username is supplied. It only says where a login goes once credentials exist.

Think of library cards issued by branches. Sam's card from the Orders branch and Sam's card from the Billing branch are two different cards, even with the same name on them. A card can still be honoured for books at other branches if it was granted that, and the login desk you show it at must be the branch that issued it. authSource tells the client which desk to walk to.

  • A MongoDB user can only read and write the database it was created in.
  • Usernames are unique across the whole deployment, so the name alone identifies a user.
  • Creating a user in admin automatically makes it an administrator.
  • Each database keeps its own users in its own system.users collection.
  • Selecting a database in driver code changes which database the login is sent to.
open as a page

In MongoDB, what do the built-in roles read, readWrite, dbAdmin and clusterAdmin each allow a user to do?

level: juniorimportance: must knowfreq 50%

basics

~20 s

In MongoDB, read queries one database's collections, and readWrite also changes them, including dropping collections. dbAdmin handles indexes, collection settings and statistics without find. clusterAdmin, held in admin, runs the deployment and has no find on application collections.

open as a page

In MongoDB, what does the server see for a field under CSFLE deterministic, CSFLE random and Queryable Encryption, and what can each still query?

level: middleimportance: must knowfreq 35%

basics

~20 s

The server stores only BinData ciphertext and never holds a key. Deterministic CSFLE allows equality because equal values encrypt identically; random CSFLE allows no value queries; Queryable Encryption stays randomized yet answers configured queries through metadata.

open as a page

In MongoDB, how do you write a custom role with db.createRole, and what limits the privileges and roles it can include?

level: middleimportance: must knowfreq 48%

basics

~20 s

db.createRole takes a role name, a privileges array and a roles array to inherit from. Outside admin, a role may only target and inherit from its own database; a role in admin can reach other databases and the cluster.

open as a page

A MongoDB user created under `use orders` logs in from mongosh, but the application's connection string has no `authSource` and gets `Authentication failed`; how do you diagnose and fix it?

level: seniorimportance: must knowfreq 44%

basics

~20 s

The shell logged in against orders, but with no authSource or path the application logs in against admin, where no such user exists. The server log shows that; fix it by adding authSource=orders to the application's connection string.

open as a page

With no `authMechanism` set, how does a MongoDB driver choose between SCRAM-SHA-256 and SCRAM-SHA-1, and what must the stored user hold for each?

level: middleimportance: should knowfreq 37%

basics

~20 s

A MongoDB driver asks in its hello with saslSupportedMechs, then uses SCRAM-SHA-256 if the reply lists it and SCRAM-SHA-1 otherwise. Each mechanism needs its own stored credential, and SCRAM-SHA-256 requires the server to digest the password.

open as a page

How does a MongoDB client log in with an X.509 certificate, and why must its user live in the `$external` database?

level: middleimportance: should knowfreq 33%

basics

~20 s

The certificate's subject, in RFC2253 form, is the username: you create that user in $external with roles and no password, then connect over TLS with authMechanism=MONGODB-X509. It lives in $external because the certificate, not MongoDB, holds the proof.

open as a page

In MongoDB, how does automatic encryption differ from explicit encryption, which editions run each, and what do crypt_shared and mongocryptd do?

level: middleimportance: should knowfreq 24%

basics

~20 s

Automatic encryption has the driver encrypt fields from a schema and needs Enterprise or Atlas; explicit encryption has your code encrypt each value and also runs on Community. crypt_shared, or mongocryptd which 9.0 deprecates, only analyses commands.

open as a page

In MongoDB in-use encryption, how do key-vault data keys relate to the customer master key, and what does deleting or rotating each do?

level: middleimportance: should knowfreq 26%

basics

~20 s

Data keys encrypt fields; the customer master key in a KMS encrypts the data keys kept in the key vault. Deleting either makes the affected fields permanently unreadable. Rotating the master key means rewrapping data keys, leaving field ciphertext untouched.

open as a page

In MongoDB Queryable Encryption, which query types can one encrypted field be configured for, and what must you fix when you create the collection?

level: middleimportance: should knowfreq 28%

basics

~20 s

A field takes equality or range, or for strings prefix, suffix or substring; only prefix and suffix combine. Query types, bounds and length limits are fixed at collection creation, and in 9.0 changing them means re-creating the collection.

open as a page

What does MongoDB's security.authorization setting turn on, and when does the localhost exception close?

level: middleimportance: should knowfreq 40%

basics

~20 s

security.authorization: enabled makes a mongod enforce roles, so clients can do only what they have been granted; the default is disabled. The localhost exception lets a loopback client create the first user, and closes once a user or role exists in admin.

open as a page

In MongoDB, what exactly is a privilege, and how do you write its resource for a collection, a database and the cluster?

level: middleimportance: should knowfreq 42%

basics

~20 s

A MongoDB privilege is a resource plus the actions allowed on it. Write the resource as { db, collection } for a collection, with an empty collection for a database's non-system collections, or as { cluster: true } for deployment-wide actions.

open as a page

How do you move a live MongoDB replica set from keyfile to X.509 member authentication without downtime, and what do the `clusterAuthMode` transition values do?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Roll members through clusterAuthMode values: sendKeyFile sends the keyfile and accepts both, sendX509 sends the certificate and accepts both, x509 accepts only certificates. Finish each step on every member first, then record the final mode in the configuration files.

open as a page

After a MongoDB service adopts client-side encryption, some queries throw errors and others quietly return wrong results, so how do you work out what the encrypted fields broke?

level: seniorimportance: should knowfreq 19%

basics

~20 s

Separate refusals from wrong answers. Automatic encryption rejects anything outside its allow-list on the client; wrong results come from the server comparing BinData, as with explicit operators, views, collation and plaintext left from before encryption.

open as a page

A MongoDB checkout service moved off a shared admin login now gets Unauthorized errors despite a readWrite grant; how do you diagnose and fix it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Read what the session really holds with connectionStatus and showPrivileges, then compare it with the action the failed command needs. Usual causes are a bare role name resolved against admin, or an action such as collMod that readWrite lacks.

open as a page

For MongoDB logins, what should a team standardise on for humans and for services, and how do you rotate service passwords without an outage?

level: principalimportance: should knowfreq 31%

basics

~20 s

Edition sets the menu: Community has SCRAM and X.509, and Enterprise adds OIDC, Kerberos and deprecated LDAP. Prefer central identity for humans and certificates or workload tokens for services. Rotate passwords with a second user, because one user cannot hold two passwords.

open as a page

For MongoDB Queryable Encryption versus application-level encryption, how do you decide when a payments service must hide card tokens and birth dates from DBAs yet search by token and birth-date range?

level: principalimportance: should knowfreq 16%

basics

~20 s

Start from the adversary and the queries. Queryable Encryption answers the range on the server, at a cost in metadata, limits and diagnostics; application-level encryption pushes search into your code. Master key loss is permanent either way.

open as a page

As a platform lead, how would you model MongoDB roles across many services on one deployment, and who may hold userAdmin?

level: principalimportance: should knowfreq 32%

basics

~20 s

Give each service its own user and a role defined in its own database, keep shared roles in admin, and confine user administration to a few guarded accounts, because userAdmin can grant its holder anything on its database, or deployment-wide on admin.

open as a page