Lesson 36 of 50 – MongoDB Authorization and Roles
72%

MongoDB Authorization and Roles

MongoDB authorization controls what an authenticated user is allowed to do in a database. It uses roles and privileges to manage access to databases, collections, and other resources.

1. What Is Authorization?

Authorization determines which operations a user can perform after their identity has been verified.

For example, consider a school management application:

User Permission
Teacher Read student records
Data Entry Operator Insert and update student records
Database Administrator Manage database users and settings

These are examples of application access policies. In MongoDB, the appropriate built-in roles or custom roles must be assigned to implement the required permissions.

2. Authentication vs Authorization

Authentication Authorization
Verifies a user's identity. Determines the user's permissions.
Checks credentials or certificates. Checks assigned roles and privileges.
Example: Is this a valid user? Example: Can this user delete a record?

Authentication and authorization work together to protect MongoDB data.

3. What Is Role-Based Access Control?

MongoDB uses Role-Based Access Control (RBAC). Instead of assigning every permission individually to every user, administrators assign roles that provide specific privileges.

For example:

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

This creates a user with read access to the school database, assuming the command is executed by a user with permission to create users.

The account does not receive general write permission from the read role.

4. Common Built-In Roles

Role Purpose
read Read data from a specified database.
readWrite Read and modify data in a specified database.
dbAdmin Perform certain database administration operations.
userAdmin Manage users and roles in a specified database.
readAnyDatabase Read data across databases, subject to role restrictions.
readWriteAnyDatabase Read and modify data across databases, subject to role restrictions.
root Provides broad administrative privileges.

Important: Roles such as root and readWriteAnyDatabase provide broad access. Do not assign them to ordinary application users unless the wider privileges are genuinely required.

5. Create a Read-Only User

Suppose a reporting application only needs to view student records. Create a user with the read role.

use school

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

The account can read data in the school database but does not receive permission to insert, update, or delete documents from this role.

Create the user only once. If the username already exists, use the appropriate user-management command instead of creating a duplicate account.

6. Create a Read-and-Write User

An application that manages student records may need read and write permissions on the school database.

use school

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

The readWrite role permits reading and modifying data in the specified database. It does not grant unrestricted administrative access to the entire MongoDB deployment.

7. Grant a Role to an Existing User

Use grantRolesToUser() to assign an additional role to an existing user.

use school

db.grantRolesToUser(
    "reportReader",
    [
        { role: "readWrite", db: "school" }
    ]
)

This example grants additional read-and-write access to the user. The account retains its existing roles and gains the new role.

A user who only needs reporting access should normally remain read-only. Grant additional privileges only when required.

8. Revoke a Role from a User

Use revokeRolesFromUser() to remove a role from an existing user.

use school

db.revokeRolesFromUser(
    "reportReader",
    [
        { role: "readWrite", db: "school" }
    ]
)

After the role is revoked, the user no longer receives permissions through that role. The user may still have permissions from other assigned roles.

9. View a User's Assigned Roles

Use getUser() to inspect a user's role assignments in the current database.

use school

db.getUser("reportReader")

To inspect the users and roles defined in the current database, you can also run:

db.getUsers()

Use these commands to check whether a user has the expected role assignments.

10. Create a Custom Role

MongoDB allows administrators to define custom roles when built-in roles do not match the application's requirements.

The following example creates a role that can find and list collections in the school database.

use school

db.createRole({
    role: "studentReportViewer",
    privileges: [
        {
            resource: {
                db: "school",
                collection: "students"
            },
            actions: ["find"]
        }
    ],
    roles: []
})

Assign the custom role to a user:

db.grantRolesToUser(
    "reportReader",
    [
        { role: "studentReportViewer", db: "school" }
    ]
)

This custom role grants the find action on the students collection. It does not grant general insert, update, or delete permissions. Additional actions must be explicitly defined if needed.

The account running these commands must have the required privileges to create roles and grant roles.

11. Best Practices for Authorization

  • Follow the principle of least privilege.
  • Use separate accounts for applications and administrators.
  • Give users access only to the databases and collections they need.
  • Avoid using the root role for everyday application tasks.
  • Review role assignments regularly.
  • Protect credentials and connection strings.
  • Use encrypted connections where appropriate.
  • Test permissions using a non-production database.

12. Practical Assignment

  1. Create a database named school.
  2. Create a user named studentReader with the read role.
  3. Create a user named schoolManager with the readWrite role.
  4. Display the assigned roles for both users.
  5. Grant an additional role to an existing user.
  6. Revoke a role and inspect the user's remaining roles.
  7. Create a custom role that permits finding student documents.
  8. Explain the difference between built-in and custom roles.
  9. Explain why application accounts should not receive unnecessary administrative permissions.

🧠 Quick Quiz

1. What does MongoDB authorization control?




2. Which role provides read access to a database?




3. Which method removes a role from a user?