Managing User Permissions in MongoDB
1. Introduction
MongoDB provides a robust security model that controls user access to databases and collections. Proper management of user permissions is crucial to ensure data security and integrity. This lesson covers key concepts and practices for managing user permissions effectively in MongoDB.
2. User Roles
MongoDB uses a role-based access control (RBAC) model. Roles are defined sets of privileges that can be assigned to users. The following are some built-in roles:
- read: Grants read access to the databases.
- readWrite: Grants read and write access.
- dbAdmin: Grants administrative privileges on the database.
- userAdmin: Grants the ability to manage users and roles.
- clusterAdmin: Grants administrative privileges across the cluster.
3. Creating Users
To create a user in MongoDB, you can use the db.createUser()
method. Below is an example of creating a user with the readWrite
role:
use myDatabase
db.createUser({
user: "myUser",
pwd: "myPassword",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
4. Assigning Permissions
Permissions can be assigned at the database level or collection level. Here’s how to assign a role to an existing user:
db.grantRolesToUser("myUser", [{ role: "dbAdmin", db: "myDatabase" }])
5. Best Practices
- Regularly review user roles and permissions.
- Use strong passwords for user accounts.
- Implement two-factor authentication (2FA) where possible.
- Monitor database access logs for suspicious activity.
- Use environment-specific users (e.g., different users for development and production).
6. FAQ
How do I see the current users and their roles?
You can run the following command:
db.getUsers()
Can I revoke a user’s role?
Yes, you can use the db.revokeRolesFromUser()
method:
db.revokeRolesFromUser("myUser", [{ role: "dbAdmin", db: "myDatabase" }])
What happens if I delete a user?
Once a user is deleted using db.dropUser()
, they can no longer access the database.