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:
- Database User Roles: Such as
read
andreadWrite
, which grant basic read or read-write permissions on a database. - Database Administration Roles: Such as
dbAdmin
,dbOwner
, anduserAdmin
, which allow various administrative actions on a database. - Cluster Administration Roles: Such as
clusterAdmin
,clusterManager
, andclusterMonitor
, which provide cluster-wide permissions. - Backup and Restoration Roles: Such as
backup
andrestore
, which allow backup and restoration activities. - All-Database Roles: Such as
readAnyDatabase
,readWriteAnyDatabase
, anduserAdminAnyDatabase
, which apply to all databases in a MongoDB instance. - 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.