Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Authorization in MongoDB

Setting up authorization and roles in MongoDB

Authorization in MongoDB determines what actions a user can perform on the database. MongoDB uses Role-Based Access Control (RBAC) to define roles and assign them to users. Each role grants specific privileges to perform actions on database resources.

Creating Roles

To set up authorization, you need to create roles that specify the permissions for users. You can create custom roles based on your application requirements.

Example: Creating a Custom Role

use admin
db.createRole({
    role: "myCustomRole",
    privileges: [
        { resource: { db: "myDatabase", collection: "" }, actions: ["find", "update"] }
    ],
    roles: []
})

Assigning Roles to Users

Once roles are created, you can assign them to users. This controls the actions users can perform on the database.

Example: Assigning a Role to a User

use admin
db.createUser({
    user: "myUser",
    pwd: "myPassword",
    roles: [{ role: "myCustomRole", db: "admin" }]
})

Built-In Roles

MongoDB provides several built-in roles that cover common use cases. Some of these roles include:

  • read: Allows read-only access to the database.
  • readWrite: Allows read and write access to the database.
  • dbAdmin: Provides administrative rights for a specific database.
  • userAdmin: Allows management of user accounts and roles.

Best Practices for Authorization

When setting up authorization, consider the following best practices:

  • Apply the principle of least privilege by granting only the necessary permissions to users.
  • Regularly review and update roles and permissions to align with changing requirements.
  • Monitor and audit user activity to detect any unauthorized access or actions.
  • Use built-in roles for common use cases to simplify role management.