Authentication and Authorization
Authentication and Authorization Interview with follow-up questions
1. What is the difference between authentication and authorization in MongoDB?
Authentication answers "who are you?" — it verifies the identity of a connecting user or client, ensuring they are who they claim to be. Authorization answers "what are you allowed to do?" — once identity is confirmed, it determines which resources and operations the principal can access.
In MongoDB terms, authentication is handled by mechanisms like SCRAM-SHA-256 (the default), x.509 certificates, LDAP, Kerberos, AWS IAM, and OIDC. Authorization is handled by Role-Based Access Control (RBAC) — built-in roles (read, readWrite, dbAdmin, userAdmin, clusterAdmin, root) plus custom roles, applied with the principle of least privilege. The two are independent: a user can authenticate successfully and still be denied an operation if their roles don't grant it. Note that Atlas enforces authentication by default, whereas a self-managed mongod requires you to explicitly enable it.
Follow-up 1
How does MongoDB implement authentication?
MongoDB provides built-in authentication mechanisms to secure access to the database. It supports various authentication methods, including username/password, X.509 certificates, LDAP, and Kerberos. By default, MongoDB uses the SCRAM-SHA-1 (Salted Challenge Response Authentication Mechanism) for username/password authentication.
Follow-up 2
What are the different types of authorization in MongoDB?
MongoDB supports several types of authorization mechanisms. The most commonly used are role-based access control (RBAC) and user-defined roles. RBAC allows administrators to define roles with specific privileges and assign them to users or groups. User-defined roles, on the other hand, provide more fine-grained control by allowing administrators to define custom roles with specific privileges.
Follow-up 3
Can you explain how role-based access control works in MongoDB?
Role-based access control (RBAC) in MongoDB allows administrators to define roles with specific privileges and assign them to users or groups. Each role can have one or more privileges, such as read, write, or administrative actions. Users can be assigned multiple roles, and the privileges of these roles are combined to determine the user's overall access rights. RBAC provides a flexible and scalable way to manage access control in MongoDB.
Follow-up 4
What is the significance of the 'admin' database in MongoDB authentication and authorization?
The 'admin' database in MongoDB has a special significance in authentication and authorization. It is the default database where users and roles are created and managed. The 'admin' database is also the database where the authentication process takes place. When a user tries to authenticate, MongoDB checks the credentials against the user documents stored in the 'admin' database. Additionally, users with the 'userAdminAnyDatabase' or 'dbAdminAnyDatabase' role in the 'admin' database have administrative privileges across all databases in the MongoDB deployment.
2. How can you enable authentication in MongoDB?
To enable authentication on a self-managed MongoDB deployment:
- Create the first admin user before locking down (or use the localhost exception). Connect, switch to
admin, and create a user-administrator:
use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(), // prompts instead of hard-coding
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
- Turn on authentication. Add to the config file (
mongod.conf):
security:
authorization: enabled
or start mongod with --auth, then restart.
- Authenticate when connecting, e.g.
mongosh -u admin -p --authenticationDatabase admin, or calldb.auth()in the shell.
Once enabled, every client must authenticate before performing operations. Key gotchas a 2026 interviewer expects: on a replica set or sharded cluster you must also configure internal authentication (a keyfile or x.509) between members, and the default mechanism is SCRAM-SHA-256. Atlas requires authentication and TLS by default, so this manual setup is mainly a self-managed concern.
Follow-up 1
What is the role of the 'mongod' command in enabling authentication?
The 'mongod' command is used to start the MongoDB server. In the context of enabling authentication, the 'mongod' command needs to be started with the --auth option. This option enables authentication by requiring clients to authenticate themselves before they can perform any operations on the server.
Follow-up 2
What are the steps to create a user in MongoDB?
To create a user in MongoDB, you can use the db.createUser() method. The steps to create a user are as follows:
Connect to the MongoDB server using a client such as the MongoDB shell.
Switch to the admin database by running the command
use admin.Use the
db.createUser()method to create the user. The method takes an object as an argument, which specifies the username, password, and roles for the user.
Here's an example of creating a user with the 'readWrite' role:
db.createUser({
user: 'myUser',
pwd: 'myPassword',
roles: [
{ role: 'readWrite', db: 'myDatabase' }
]
})
Follow-up 3
Can you explain the use of the 'db.createUser()' method in MongoDB?
The db.createUser() method in MongoDB is used to create a user with specified roles and privileges. This method is typically used when enabling authentication and setting up user accounts.
The method takes an object as an argument, which specifies the username, password, and roles for the user. The roles can be specified as an array of objects, where each object represents a role and the associated database.
Here's an example of creating a user with the 'readWrite' role:
db.createUser({
user: 'myUser',
pwd: 'myPassword',
roles: [
{ role: 'readWrite', db: 'myDatabase' }
]
})
Follow-up 4
What are the potential issues that might arise when enabling authentication in MongoDB and how can they be resolved?
Enabling authentication in MongoDB can introduce some potential issues. Here are a few common issues and their resolutions:
Locked out of the database: If you forget the username or password of the user with administrative privileges, you may get locked out of the database. To resolve this, you can start the MongoDB server without authentication enabled and then create a new user with administrative privileges.
Connection failures: If clients are not able to connect to the MongoDB server after enabling authentication, it could be due to incorrect authentication credentials or missing user privileges. Double-check the credentials and make sure the user has the necessary roles and privileges.
Performance impact: Enabling authentication can introduce some performance overhead due to the additional authentication checks. If you experience performance issues, you can consider optimizing the authentication configuration or upgrading the hardware.
It's important to plan and test the authentication setup before enabling it in a production environment.
3. What is role-based access control in MongoDB?
Role-Based Access Control (RBAC) is MongoDB's authorization model: you grant access by assigning roles to users rather than permissions directly. Each role bundles a set of privileges, where a privilege is a resource (a database, collection, or cluster) paired with the actions allowed on it (e.g. find, insert, update, createIndex).
MongoDB ships built-in roles — read, readWrite, dbAdmin, userAdmin, clusterAdmin, the *AnyDatabase variants, and the superuser root — and lets you define custom roles with db.createRole() when the built-ins are too broad. Roles can also inherit from other roles. The interviewer's follow-up is usually about least privilege: give each user the narrowest role that does the job (e.g. readWrite on one database, not root), and scope roles per-database. Atlas adds its own project/organization-level roles layered on top of database RBAC.
Follow-up 1
How can you assign roles to a user in MongoDB?
To assign roles to a user in MongoDB, you can use the db.grantRolesToUser() method. This method allows you to grant one or more roles to a user. Here's an example:
use admin
db.grantRolesToUser(
"username",
[
{ role: "role1", db: "database1" },
{ role: "role2", db: "database2" }
]
)
Follow-up 2
What are built-in roles in MongoDB?
MongoDB provides several built-in roles that you can use to assign privileges to users. Some of the commonly used built-in roles include:
read: Provides read-only access to a database or collection.readWrite: Provides read and write access to a database or collection.dbAdmin: Provides administrative access to a database.userAdmin: Provides administrative access to manage users and roles.
You can find a complete list of built-in roles in the MongoDB documentation.
Follow-up 3
Can you create custom roles in MongoDB? If yes, how?
Yes, you can create custom roles in MongoDB. To create a custom role, you can use the db.createRole() method. This method allows you to define the privileges and roles for the custom role. Here's an example:
use admin
db.createRole({
role: "customRole",
privileges: [
{ resource: { db: "database1", collection: "collection1" }, actions: ["find", "insert"] }
],
roles: []
})
Follow-up 4
How does role inheritance work in MongoDB?
Role inheritance in MongoDB allows you to create roles that inherit privileges from other roles. When a user is assigned a role that has inherited privileges, they will have access to all the privileges of the inherited roles as well. This simplifies the process of managing access control by allowing you to define roles with common sets of privileges and assign them to users.
To create a role that inherits privileges, you can specify the roles field in the db.createRole() method. For example:
use admin
db.createRole({
role: "roleWithInheritance",
privileges: [],
roles: ["role1", "role2"]
})
4. What is the purpose of the 'db.auth()' method in MongoDB?
db.auth() authenticates a user against the current database from within mongosh. You pass credentials and it verifies them against the stored user record; on success, the connection gains that user's roles and privileges for the rest of the session.
use admin
db.auth("admin", passwordPrompt()) // returns 1 on success
You'd use it when you connected without credentials and want to authenticate interactively, or to switch identity mid-session. A couple of points an interviewer may probe: authentication is tied to the authentication database where the user was created (often admin), so you use that database first or pass it explicitly; and in practice you usually authenticate at connect time via the connection string / -u -p --authenticationDatabase flags rather than calling db.auth() by hand. Prefer passwordPrompt() over a literal password so it never lands in shell history.
Follow-up 1
Can you explain the syntax and usage of the 'db.auth()' method?
The syntax of the 'db.auth()' method in MongoDB is as follows:
db.auth(username, password)
The 'db.auth()' method is called on a specific database object (e.g., 'db') and takes two parameters: 'username' and 'password'. The method verifies the provided credentials against the user credentials stored in the database's system.users collection. If the authentication is successful, the method returns 1; otherwise, it throws an error.
Follow-up 2
What are the potential issues that might arise when using the 'db.auth()' method and how can they be resolved?
There are a few potential issues that might arise when using the 'db.auth()' method in MongoDB:
Authentication failure: If the provided username or password is incorrect, the method will throw an error. To resolve this issue, double-check the credentials and ensure they are correct.
User not found: If the specified user does not exist in the database's system.users collection, the method will throw an error. To resolve this issue, create the user with the correct credentials using the 'db.createUser()' method.
Insufficient privileges: If the authenticated user does not have sufficient privileges to perform the desired operations, the method will throw an error. To resolve this issue, grant the necessary privileges to the user using the 'db.grantRolesToUser()' method.
Follow-up 3
How can you authenticate a user in MongoDB using a script?
To authenticate a user in MongoDB using a script, you can use the following code example:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const username = 'myuser';
const password = 'mypassword';
MongoClient.connect(url, function(err, client) {
if (err) throw err;
const db = client.db(dbName);
db.auth(username, password, function(err, result) {
if (err) throw err;
console.log('Authentication successful');
// Perform operations on the database
client.close();
});
});
In this example, we first create a MongoClient object and specify the MongoDB connection URL and the name of the database. We then call the 'db.auth()' method on the database object, passing in the username and password as parameters. If the authentication is successful, we can proceed to perform operations on the database. Finally, we close the MongoDB client connection.
5. How can you manage user accounts in MongoDB?
User accounts in MongoDB are managed with these shell methods (run against the user's authentication database, usually admin):
- Create a user:
db.createUser()specifies the username, password, and roles.
db.createUser({
user: "appUser",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "shop" } ]
})
Change a password:
db.changeUserPassword("appUser", passwordPrompt()).Grant roles:
db.grantRolesToUser("appUser", [ { role: "read", db: "reports" } ]).Revoke roles:
db.revokeRolesFromUser("appUser", [ { role: "read", db: "reports" } ]).Update or inspect:
db.updateUser()changes roles/custom data in one call;db.getUsers()lists users.Delete a user:
db.dropUser("appUser").
Follow least privilege when assigning roles, and use passwordPrompt() to avoid putting secrets in history. On Atlas you typically don't run these directly — database users are managed through the Atlas UI/Admin API (and you can use SCRAM, x.509, or AWS IAM/LDAP/OIDC identities instead of passwords).
Follow-up 1
What are the steps to change a user's password in MongoDB?
To change a user's password in MongoDB, you can follow these steps:
- Connect to the MongoDB server using a MongoDB client.
- Switch to the database where the user account exists using the
usecommand. - Execute the
db.changeUserPassword()method with the username, current password, and new password as parameters.
Here's an example:
use admin
db.changeUserPassword('myuser', 'oldpassword', 'newpassword')
Follow-up 2
How can you delete a user in MongoDB?
To delete a user in MongoDB, you can use the db.dropUser() method. This method requires the username of the user to be deleted.
Here's an example:
use admin
db.dropUser('myuser')
Follow-up 3
What is the purpose of the 'db.dropUser()' method in MongoDB?
The db.dropUser() method in MongoDB is used to delete a user account. It requires the username of the user to be deleted as a parameter.
Here's an example:
use admin
db.dropUser('myuser')
Follow-up 4
Can you explain the use of the 'db.updateUser()' method in MongoDB?
The db.updateUser() method in MongoDB is used to update the properties of a user account. It allows you to modify the username, password, and roles of a user.
Here's an example:
use admin
db.updateUser('myuser', { $set: { password: 'newpassword' } })
Live mock interview
Mock interview: Authentication and Authorization
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.