Skip to main content

Architecture

Role-Based Access Control (RBAC) in MongoDB is a security feature that controls access to resources and operations based on roles. A role grants privileges that dictate what actions a user can perform on which resources. MongoDB provides a variety of built-in roles and also allows you to define custom roles tailored to your specific needs.

Built-in Roles

MongoDB offers several built-in roles, each designed for specific use-cases:

  1. Database User Roles: Such as read and readWrite, which grant basic read or read-write permissions on a database.
  2. Database Administration Roles: Such as dbAdmin, dbOwner, and userAdmin, which allow various administrative actions on a database.
  3. Cluster Administration Roles: Such as clusterAdmin, clusterManager, and clusterMonitor, which provide cluster-wide permissions.
  4. Backup and Restoration Roles: Such as backup and restore, which allow backup and restoration activities.
  5. All-Database Roles: Such as readAnyDatabase, readWriteAnyDatabase, and userAdminAnyDatabase, which apply to all databases in a MongoDB instance.
  6. Superuser Roles: Such as root, which provides full access to all MongoDB resources and actions.

Creating Users with Roles

You can create a user and assign roles using the createUser command:

db.createUser({
user: "myUser",
pwd: "myPassword",
roles: [
{ role: "readWrite", db: "myDatabase" },
{ role: "read", db: "anotherDatabase" }
]
});

Custom Roles

You can create custom roles using the createRole command:

db.createRole({
role: "customRole",
privileges: [
{
resource: { db: "myDatabase", collection: "myCollection" },
actions: ["find", "update"]
}
],
roles: []
});

Assigning and Revoking Roles

You can modify user roles using the grantRolesToUser and revokeRolesFromUser commands:

// Grant roles
db.grantRolesToUser("myUser", [{ role: "dbAdmin", db: "myDatabase" }]);

// Revoke roles
db.revokeRolesFromUser("myUser", [{ role: "read", db: "anotherDatabase" }]);

Role Inheritance

Roles can inherit privileges from other roles:

db.createRole({
role: "parentRole",
privileges: [],
roles: ["customRole", "read"]
});

Considerations

  • Least Privilege: Assign only the roles that are necessary for a user to perform their tasks.

  • Auditing: Regularly review and audit roles and permissions to ensure they align with your security policies.

  • Role Isolation: Separate administrative roles from data access roles to minimize the risk of unauthorized data manipulation.