Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 35
→

MongoDB User Roles and Authentication: Secure Your Database

MongoDB User Roles and Authentication: Secure Your Database

November 6, 2026

MongoDB User Roles and Authentication: Secure Your Database

Introduction

Database security is one of the most important aspects of application development. When an application stores sensitive information such as user accounts, passwords, customer records and business data, protecting database access becomes essential.

MongoDB provides security features that help developers control who can connect to a database and what operations they are allowed to perform.

MongoDB uses Authentication and Authorization to protect database resources.

  • Authentication: Verifies the identity of a user before allowing access.

  • Authorization: Determines what an authenticated user can do inside the database.

MongoDB also provides Role-Based Access Control (RBAC), which allows database administrators to assign permissions through built-in roles and custom roles.

In this tutorial, you will learn how to create MongoDB users, assign roles, authenticate users, enable access control, manage permissions and secure your database with practical examples.

1. What Is MongoDB Authentication?

MongoDB Authentication is a security mechanism that verifies the identity of a user or application before granting access to a MongoDB deployment.

Without proper authentication, an accessible MongoDB server may allow unauthorized users to connect and access database resources.

MongoDB supports different authentication mechanisms, including:

  1. SCRAM Authentication

  2. X.509 Certificate Authentication

  3. Kerberos Authentication

  4. LDAP Authentication

  5. OIDC Authentication

  6. AWS IAM Authentication

For beginners, we will mainly use SCRAM username and password authentication.

Example:

A database administrator creates a user with:

  • Username: adminUser

  • Password: A strong private password

  • Role: Database administration permissions

When someone tries to connect using this account, MongoDB verifies the supplied credentials.

If the credentials are valid, the user is authenticated.

2. What Is MongoDB Authorization?

Authorization determines which database operations an authenticated user is permitted to perform.

For example:

  • A read-only user can view records.

  • A readWrite user can insert, retrieve, update and delete records.

  • A database administrator can perform specific database management operations.

  • A user administrator can manage users and roles.

MongoDB implements authorization using Role-Based Access Control (RBAC).

A user receives permissions through one or more roles.

Example:

A company has three employees:

User Role Permission
Rahul read View records
Amit readWrite Read and modify records
Priya dbAdmin Database administration

This approach helps prevent unauthorized database operations.

3. Authentication vs Authorization

Authentication and authorization are related, but they perform different functions.

Authentication Authorization
Verifies user identity Checks user permissions
Uses credentials or another authentication mechanism Uses roles and privileges
Answers: Who are you? Answers: What can you do?
Happens during authentication Determines access to database operations

Example:

Suppose Rahul logs in using a valid MongoDB username and password.

  • Authentication confirms that Rahul is a valid user.

  • Authorization checks whether Rahul has permission to read or modify the requested data.

Both mechanisms are necessary for effective database security.

4. What Is Role-Based Access Control (RBAC)?

RBAC stands for Role-Based Access Control.

It is a security system in which users receive permissions through assigned roles instead of assigning every permission individually.

MongoDB roles contain privileges that define:

  • Which resources a user can access.

  • Which actions a user can perform.

  • Which database or collection is covered by those permissions.

The basic structure is:

User → Role → Privileges → Database Resources

For example:

A user named Rahul receives the readWrite role on collegeDB.

This allows Rahul to read and modify data in that database.

MongoDB supports two major types of roles:

  1. Built-in Roles

  2. User-Defined Roles (Custom Roles)

5. Understanding MongoDB Built-in Roles

MongoDB provides several built-in roles for common database tasks.

Some important built-in roles are:

1. read

The read role provides read-only access to a database.

A user with this role can retrieve documents but cannot perform normal insert, update or delete operations.

Example:

{
    role: "read",
    db: "collegeDB"
}

2. readWrite

The readWrite role provides read and write permissions on a database.

It allows users to:

  • Retrieve documents.

  • Insert documents.

  • Update documents.

  • Delete documents.

  • Perform other permitted data operations.

Example:

{
    role: "readWrite",
    db: "collegeDB"
}

3. dbAdmin

The dbAdmin role provides database administration privileges.

It allows users to perform certain database management operations, such as managing indexes and collecting database statistics.

It does not provide full read and write access to application data.

Example:

{
    role: "dbAdmin",
    db: "collegeDB"
}

4. userAdmin

The userAdmin role provides permissions to create and manage users and roles on a particular database.

It allows operations such as:

  • Creating users.

  • Updating user information.

  • Granting roles.

  • Revoking roles.

  • Managing database users.

Important: A user with userAdmin can grant privileges to themselves. Assign this role carefully.

5. dbOwner

The dbOwner role combines the permissions of:

  • readWrite

  • dbAdmin

  • userAdmin

It provides broad administrative access to the specified database.

6. root

The root role provides extensive administrative privileges across the MongoDB deployment.

It combines permissions from several administrative and database roles.

Use this role only when full administrative access is genuinely required.

Important: The built-in roles listed above are for self-managed MongoDB deployments. MongoDB Atlas provides its own database-user role options.

6. Create a MongoDB Database User

Now let's create a database user using MongoDB Shell (mongosh).

First, open MongoDB Compass or connect using mongosh.

Run:

mongosh

Switch to the admin database:

use admin

Now create an administrator user:

db.createUser({
    user: "myUserAdmin",
    pwd: passwordPrompt(),
    roles: [
        {
            role: "userAdminAnyDatabase",
            db: "admin"
        }
    ]
})

MongoDB asks you to enter a password securely through the shell prompt.

Explanation

  • db.createUser() creates a new database user.

  • user defines the username.

  • pwd specifies the password.

  • passwordPrompt() asks for the password without placing it directly in the command.

  • roles specifies the permissions assigned to the user.

  • userAdminAnyDatabase allows user administration across databases.

If successful, MongoDB returns a result similar to:

{
    ok: 1
}

Note: This example assumes the initial administrator is being created through the localhost exception after access control is enabled. The localhost exception is available only during initial setup when no users or roles exist.

7. Enable Authentication in MongoDB

MongoDB self-managed deployments do not enable access control by default.

We must enable authorization to require users to authenticate before accessing protected database resources.

Step 1: Locate the MongoDB Configuration File

Find the MongoDB configuration file named:

mongod.cfg

The location depends on your MongoDB installation.

Step 2: Open the Configuration File

Open mongod.cfg using a text editor with the required administrator permissions.

Step 3: Add the Security Configuration

Add the following settings:

security:
  authorization: enabled

Step 4: Save the File

Save the configuration file.

Step 5: Restart MongoDB Server

Restart the MongoDB service so the updated configuration takes effect.

On Windows, you can restart the MongoDB service through the Services application.

Step 6: Connect to MongoDB

Open mongosh:

mongosh

During initial local setup, the localhost exception allows the first administrator user to be created without credentials, provided no users or roles have been created yet.

After creating the first user, this exception is disabled.

Important: If your MongoDB server already has users, do not change authentication settings without first verifying that you have working administrator credentials. Otherwise, you may lose access.

8. Create a User with readWrite Role

Now let's create a separate application user who can access the collegeDB database.

First, authenticate as the administrator.

mongosh -u myUserAdmin --authenticationDatabase admin -p

Enter the administrator password when prompted.

Switch to the database:

use collegeDB

Create a new user:

db.createUser({
    user: "collegeUser",
    pwd: passwordPrompt(),
    roles: [
        {
            role: "readWrite",
            db: "collegeDB"
        }
    ]
})

Explanation

  • collegeUser is the new username.

  • passwordPrompt() securely requests the password.

  • readWrite provides read and write permissions.

  • collegeDB is the database where the role applies.

Now this user can perform permitted read and write operations on the collegeDB database.

9. Connect to MongoDB Using Authentication

After creating the user, we can connect to MongoDB using the new credentials.

Open a new terminal and run:

mongosh -u collegeUser --authenticationDatabase collegeDB -p

Enter the password when prompted.

If authentication succeeds, you will be connected as collegeUser.

Now switch to the database:

use collegeDB

Insert a sample document:

db.students.insertOne({
    name: "Rahul",
    age: 22,
    course: "MongoDB"
})

Retrieve the document:

db.students.find()

Because this user has the readWrite role, these operations are permitted.

Important: Exit the previous mongosh session before testing a different user. Authenticating another user in the same session can add privileges rather than replace the existing authenticated identity.

10. Create a Read-Only MongoDB User

Sometimes an application needs to display database records without allowing users to modify them.

For this purpose, MongoDB provides the read role.

Example:

use collegeDB

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

Now connect using:

mongosh -u studentViewer --authenticationDatabase collegeDB -p

Retrieve records:

db.students.find()

This operation is allowed.

But try inserting a document:

db.students.insertOne({
    name: "Amit",
    age: 23
})

MongoDB will reject the operation because the user does not have insert permission.

This is useful for reporting applications and read-only dashboards.

11. View MongoDB Users

You can display users created in the current authentication database using:

show users

You can also retrieve information about a particular user:

db.getUser("collegeUser")

To inspect user information and assigned roles:

db.runCommand({
    usersInfo: "collegeUser",
    showPrivileges: true
})

This helps administrators understand which permissions have been assigned to a user.

12. Update a MongoDB User Password

MongoDB allows administrators to change the password of an existing user.

Example:

use collegeDB

db.updateUser(
    "collegeUser",
    {
        pwd: passwordPrompt()
    }
)

MongoDB asks for the new password.

This is useful when a password needs to be changed because of a security policy or suspected credential exposure.

13. Grant Additional Roles to a User

You can assign additional roles to an existing user.

Example:

use collegeDB

db.grantRolesToUser(
    "collegeUser",
    [
        {
            role: "dbAdmin",
            db: "collegeDB"
        }
    ]
)

Now the user has both:

  • readWrite

  • dbAdmin

This gives the user additional database administration permissions.

Remember that adding a role increases privileges; it does not remove the permissions of existing roles.

14. Revoke a Role from a User

If a user no longer needs a particular permission, you can revoke the assigned role.

Example:

use collegeDB

db.revokeRolesFromUser(
    "collegeUser",
    [
        {
            role: "dbAdmin",
            db: "collegeDB"
        }
    ]
)

The dbAdmin role is removed from the user.

The user still retains any other roles that have not been revoked.

15. Delete a MongoDB User

If a database user is no longer required, you can remove that user.

Example:

use collegeDB

db.dropUser("studentViewer")

If successful, MongoDB returns:

true

This removes the user from the specified authentication database.

Important: Removing a user does not delete the database or its documents.

16. Create a Custom Role in MongoDB

Built-in roles cover many common requirements. However, sometimes an application needs a more specific permission structure.

For example:

Suppose a developer should be allowed to:

  • Read student records.

  • Insert student records.

  • Update student records.

  • Not delete student records.

  • Not manage database users.

We can create a custom role for this requirement.

Switch to the database:

use collegeDB

Create the custom role:

db.createRole({
    role: "studentManager",
    privileges: [
        {
            resource: {
                db: "collegeDB",
                collection: "students"
            },
            actions: [
                "find",
                "insert",
                "update"
            ]
        }
    ],
    roles: []
})

Explanation

  • createRole() creates a custom role.

  • role specifies the role name.

  • privileges defines allowed operations.

  • resource identifies the database and collection.

  • actions specifies the permitted operations.

  • roles: [] means the custom role does not inherit another role.

This role does not grant the remove action on the students collection.

17. Assign the Custom Role to a User

After creating the custom role, assign it to a user.

Example:

db.createUser({
    user: "studentManagerUser",
    pwd: passwordPrompt(),
    roles: [
        {
            role: "studentManager",
            db: "collegeDB"
        }
    ]
})

Now the user receives the custom permissions defined in studentManager.

This is a practical example of implementing least-privilege access control.

18. MongoDB Security Best Practices

Follow these security practices when working with MongoDB.

1. Enable Authentication

Enable authorization on self-managed MongoDB deployments so users must authenticate before accessing protected resources.

2. Use Strong Passwords

Create strong and unique passwords for administrator and application accounts.

3. Follow the Principle of Least Privilege

Assign users only the permissions required to perform their tasks.

Avoid giving every user the root role.

4. Create Separate Database Users

Use different database accounts for applications, developers, administrators and reporting tools.

5. Restrict Network Access

Allow connections only from trusted systems and required IP addresses.

Do not expose MongoDB ports publicly without appropriate network protection.

6. Protect Connection Strings

Never publish MongoDB usernames, passwords or connection strings in public source-code repositories.

Use environment variables or secure secret-management systems.

7. Use TLS Encryption

Use TLS to protect communication between applications and MongoDB servers.

8. Review User Permissions Regularly

Check assigned roles and remove unnecessary privileges.

9. Keep MongoDB Updated

Use supported MongoDB versions and apply relevant security updates.

10. Monitor Database Activity

Review logs and monitor database access for unusual or unauthorized activity.

19. MongoDB Atlas Authentication and Security

MongoDB Atlas is a cloud-based MongoDB database service.

It provides a web-based interface for managing database users and network access.

Follow these steps:

  1. Open MongoDB Atlas.

  2. Sign in to your account.

  3. Select your project.

  4. Open the Security section.

  5. Navigate to Database Access.

  6. Select Add New Database User.

  7. Enter a username and password.

  8. Select the required database-user role.

  9. Save the user.

  10. Configure Network Access to allow trusted IP addresses.

Important Difference Between Atlas Users and Database Users

MongoDB Atlas has two different account types:

Atlas Users: These accounts access and manage the Atlas web application and projects.

Database Users: These accounts authenticate applications and clients that connect to MongoDB databases.

They are not the same accounts.

Also, Atlas database users should be created and managed through the Atlas-supported interface or APIs, rather than assuming that self-managed db.createUser() workflows apply to Atlas.

20. Practical Example: MongoDB User Permission Structure

Let's consider a college management application.

The application has three users:

Username Assigned Role Access
adminUser Administrative role User management
collegeUser readWrite Read and modify college data
studentViewer read View student records

This structure provides different levels of database access according to each user's responsibilities.

For example:

  • Administrators manage database users.

  • Application users manage student records.

  • Reporting users view information without changing it.

This makes the application easier to manage and more secure.

21. Common MongoDB Authentication Errors and Solutions

Error 1: Authentication Failed

Reason: The username, password or authentication database may be incorrect.

Solution:

  • Verify the username.

  • Check the password.

  • Verify the authentication database.

  • Confirm the user's assigned credentials.

Error 2: Unauthorized Operation

Reason: The authenticated user does not have sufficient privileges.

Solution:

Check the user's assigned roles:

db.getUser("collegeUser")

Ask an authorized administrator to grant the required role.

Error 3: Authentication Is Not Enabled

Reason: MongoDB authorization may not be enabled on the self-managed server.

Solution:

Check the MongoDB configuration file:

security:
  authorization: enabled

Restart the MongoDB service after making configuration changes.

Error 4: User Already Exists

Reason: A user with the same username and authentication database already exists.

Solution:

Check existing users:

show users

Update the existing account if necessary instead of creating a duplicate.

Error 5: Cannot Connect to MongoDB

Reason: The MongoDB service may be stopped, the connection URI may be incorrect, or network access may be restricted.

Solution:

  • Check whether MongoDB Server is running.

  • Verify the port number.

  • Check the connection URI.

  • Verify firewall and network settings.

22. Practical Exercises

Practice the following exercises to understand MongoDB authentication and authorization.

Exercise 1: Create an administrator user in MongoDB.

Exercise 2: Enable authorization in the MongoDB configuration file.

Exercise 3: Create a database named companyDB.

Exercise 4: Create a user named employeeUser with the readWrite role on companyDB.

Exercise 5: Create another user named reportUser with the read role.

Exercise 6: Connect to MongoDB using both user accounts.

Exercise 7: Test whether the read-only user can insert documents.

Exercise 8: Update an existing user's password.

Exercise 9: Grant an additional role to an existing user.

Exercise 10: Create a custom role that allows reading and updating documents but does not allow deletion.

23. Frequently Asked Questions (FAQs)

Q1. What is authentication in MongoDB?

Authentication verifies the identity of a user or application before allowing it to access a MongoDB deployment.

Q2. What is authorization in MongoDB?

Authorization determines which database operations an authenticated user is permitted to perform.

Q3. What is RBAC in MongoDB?

RBAC stands for Role-Based Access Control. It manages database permissions by assigning roles to users.

Q4. How do I create a MongoDB user?

Use the db.createUser() method in mongosh on a self-managed MongoDB deployment.

Q5. What is the difference between read and readWrite roles?

The read role allows users to retrieve data, while readWrite allows users to read and modify data in the specified database.

Q6. What is the root role in MongoDB?

The root role provides extensive administrative privileges across a self-managed MongoDB deployment.

Q7. Can we create custom roles in MongoDB?

Yes. Use the db.createRole() method to define specific privileges for a custom role.

Q8. How can I enable authentication in MongoDB?

Enable authorization through the MongoDB configuration file using:

security:
  authorization: enabled

Restart the MongoDB server after updating the configuration.

Q9. Can MongoDB have multiple users?

Yes. MongoDB supports multiple database users with different roles and permissions.

Q10. Is MongoDB Atlas authentication different from local MongoDB authentication?

Both support database-user authentication, but Atlas provides its own interface and role-management options. Atlas users and database users are separate account types.

Conclusion

MongoDB User Roles and Authentication are essential features for protecting database information and controlling access to database resources.

In this tutorial, we learned about authentication, authorization, Role-Based Access Control (RBAC), built-in roles, custom roles, user creation, password management and permission assignment.

We also learned how to enable access control, connect using authenticated users, grant and revoke roles, delete users and configure MongoDB Atlas database access.

By following the principle of least privilege and applying appropriate security practices, developers can build safer and more reliable MongoDB applications.

Practice these commands in your local MongoDB environment to strengthen your understanding of database security.

←
Post 28 of 35
→