阿里云主机折上折
  • 微信号
Current Site:Index > Role and permission management (built-in roles, custom roles)

Role and permission management (built-in roles, custom roles)

Author:Chuan Chen 阅读数:21401人阅读 分类: MongoDB

Basic Concepts of Role and Permission Management

MongoDB's permission system is built on roles and privileges. A role is a collection of privileges that can be assigned to users. Privileges define allowed operations on specific resources. MongoDB provides built-in roles and also supports creating custom roles to meet specific requirements.

Privileges consist of resources and actions. Resources can be databases, collections, clusters, or specific documents; actions include CRUD operations like find, insert, update, delete, as well as administrative operations like createCollection, dropDatabase, etc.

Types of Built-in Roles

MongoDB's built-in roles are divided into the following categories:

  1. Database User Roles:

    • read: Allows reading non-system collections in a specified database
    • readWrite: Provides all permissions of the read role plus write permissions
  2. Database Administration Roles:

    • dbAdmin: Allows performing administrative operations like index creation, statistics collection
    • userAdmin: Allows creating and modifying users and roles in the current database
    • dbOwner: Combines readWrite, dbAdmin, and userAdmin roles
  3. Cluster Administration Roles:

    • clusterAdmin: Provides maximum cluster management access
    • clusterManager: Provides permissions to monitor and manage the cluster
    • clusterMonitor: Provides read-only access to monitoring tools
    • hostManager: Allows monitoring and managing servers
  4. Backup and Restoration Roles:

    • backup: Provides permissions needed for data backup
    • restore: Provides permissions needed to restore data from backups
  5. All-Database Roles:

    • readAnyDatabase: Provides read-only permissions for all databases
    • readWriteAnyDatabase: Provides read-write permissions for all databases
    • userAdminAnyDatabase: Provides userAdmin permissions for all databases
    • dbAdminAnyDatabase: Provides dbAdmin permissions for all databases
  6. Superuser Roles:

    • root: Provides full access to all resources

Creating Custom Roles

When built-in roles do not meet requirements, custom roles can be created. Creating a role requires specifying:

  1. Role name
  2. The database where the role resides
  3. Privileges
  4. Inherited roles
// Example of creating a custom role
use admin
db.createRole({
  role: "appAdmin",
  privileges: [
    {
      resource: { db: "appDB", collection: "" },
      actions: ["find", "insert", "update", "remove", "createIndex"]
    },
    {
      resource: { db: "appDB", collection: "logs" },
      actions: ["find"]
    }
  ],
  roles: [
    { role: "read", db: "config" }
  ]
})

Role Management Operations

Common role management commands include:

  1. View all roles:
db.getRoles({ showBuiltinRoles: true })
  1. View a specific role:
db.getRole("appAdmin", { showPrivileges: true })
  1. Update a role:
db.updateRole("appAdmin", {
  privileges: [
    {
      resource: { db: "appDB", collection: "" },
      actions: ["find", "insert", "update", "remove", "createIndex", "dropIndex"]
    }
  ],
  roles: [
    { role: "read", db: "config" },
    { role: "read", db: "local" }
  ]
})
  1. Delete a role:
db.dropRole("appAdmin")

User and Role Assignment

Roles can be assigned when creating a user:

use admin
db.createUser({
  user: "appUser",
  pwd: "securePassword123",
  roles: [
    { role: "appAdmin", db: "admin" },
    { role: "readWrite", db: "appData" }
  ]
})

Roles can also be added or removed for a user later:

// Add roles
db.grantRolesToUser("appUser", [
  { role: "dbAdmin", db: "appDB" }
])

// Remove roles
db.revokeRolesFromUser("appUser", [
  { role: "readWrite", db: "appData" }
])

Permission Inheritance and Composition

Roles can inherit permissions from other roles, forming a hierarchy:

// Create a base role
db.createRole({
  role: "baseRole",
  privileges: [
    {
      resource: { db: "appDB", collection: "users" },
      actions: ["find", "insert"]
    }
  ],
  roles: []
})

// Create an extended role
db.createRole({
  role: "extendedRole",
  privileges: [
    {
      resource: { db: "appDB", collection: "users" },
      actions: ["update", "remove"]
    }
  ],
  roles: [
    { role: "baseRole", db: "admin" }
  ]
})

Best Practices

  1. Principle of Least Privilege: Grant only the minimum permissions necessary to complete tasks
  2. Role Layering: Create base roles and extended roles to avoid duplicate permission definitions
  3. Regular Audits: Periodically review user and role assignments
  4. Environment Isolation: Use different roles and permissions for development, testing, and production environments
  5. Documentation: Maintain documentation for roles and permissions

Practical Application Scenarios

E-commerce Platform Permission Design:

// Product management role
db.createRole({
  role: "productManager",
  privileges: [
    {
      resource: { db: "ecommerce", collection: "products" },
      actions: ["find", "insert", "update"]
    },
    {
      resource: { db: "ecommerce", collection: "categories" },
      actions: ["find", "insert", "update"]
    }
  ],
  roles: []
})

// Order processing role
db.createRole({
  role: "orderProcessor",
  privileges: [
    {
      resource: { db: "ecommerce", collection: "orders" },
      actions: ["find", "update"]
    },
    {
      resource: { db: "ecommerce", collection: "customers" },
      actions: ["find"]
    }
  ],
  roles: []
})

// Administrator role (inherits multiple roles)
db.createRole({
  role: "ecommerceAdmin",
  privileges: [
    {
      resource: { db: "ecommerce", collection: "" },
      actions: ["createCollection", "dropCollection"]
    }
  ],
  roles: [
    { role: "productManager", db: "admin" },
    { role: "orderProcessor", db: "admin" },
    { role: "dbAdmin", db: "ecommerce" }
  ]
})

Permission Verification and Testing

Methods to verify user permissions:

// Simulate user operations
db.auth("appUser", "securePassword123")

// Check permissions
db.runCommand({
  rolesInfo: { role: "appAdmin", db: "admin" },
  showPrivileges: true
})

// Test if specific operations are allowed
try {
  db.getSiblingDB("appDB").products.insertOne({ name: "Test" })
  print("Insert operation allowed")
} catch (e) {
  print("Insert operation denied: " + e.message)
}

Cross-Database Permission Management

Managing permissions across multiple databases:

// Create a cross-database role
db.createRole({
  role: "multiDBAnalyst",
  privileges: [
    {
      resource: { db: "sales", collection: "" },
      actions: ["find"]
    },
    {
      resource: { db: "inventory", collection: "" },
      actions: ["find"]
    },
    {
      resource: { db: "reports", collection: "monthly" },
      actions: ["find", "insert", "update"]
    }
  ],
  roles: []
})

// Assign to a user
db.updateUser("analystUser", {
  roles: [
    { role: "multiDBAnalyst", db: "admin" },
    { role: "read", db: "shared" }
  ]
})

Permission and Collection-Level Control

Fine-grained control at the collection level:

// Special permissions for financial data
db.createRole({
  role: "financialAccess",
  privileges: [
    {
      resource: { db: "corporate", collection: "transactions" },
      actions: ["find", "insert"]
    },
    {
      resource: { db: "corporate", collection: "salaries" },
      actions: ["find"]
    },
    {
      resource: { db: "corporate", collection: "auditLogs" },
      actions: ["find", "insert", "update"]
    }
  ],
  roles: []
})

// Restricted financial role
db.createRole({
  role: "financialReadOnly",
  privileges: [
    {
      resource: { db: "corporate", collection: "transactions" },
      actions: ["find"]
    },
    {
      resource: { db: "corporate", collection: "auditLogs" },
      actions: ["find"]
    }
  ],
  roles: []
})

System Collection Permission Management

System collections require special permissions:

// Allow access to system.profile collection
db.createRole({
  role: "profileAccess",
  privileges: [
    {
      resource: { db: "", collection: "system.profile" },
      actions: ["find"]
    }
  ],
  roles: []
})

// Allow modification of system.users collection
db.createRole({
  role: "userManagement",
  privileges: [
    {
      resource: { db: "admin", collection: "system.users" },
      actions: ["find", "insert", "update", "remove"]
    },
    {
      resource: { db: "admin", collection: "system.roles" },
      actions: ["find", "insert", "update", "remove"]
    }
  ],
  roles: []
})

Permission and Application Integration

Integrating MongoDB permissions in a Node.js application:

const { MongoClient } = require('mongodb');

async function connectWithRoles() {
  const client = new MongoClient('mongodb://appUser:securePassword123@localhost:27017/admin');
  
  try {
    await client.connect();
    const db = client.db('appDB');
    
    // Perform permission-restricted operations
    const result = await db.collection('products').insertOne({
      name: 'New Product',
      price: 99.99
    });
    
    console.log('Insert result:', result);
    
    // Attempt an operation without permission
    try {
      await db.dropCollection('products');
    } catch (err) {
      console.log('Expected error (no drop permission):', err.message);
    }
    
  } finally {
    await client.close();
  }
}

connectWithRoles().catch(console.error);

Common Issues in Permission Management

  1. Permission Caching: MongoDB caches permission information; reauthentication may be required after modifying permissions
  2. Permission Conflicts: Multiple roles may have conflicting permissions, with deny taking precedence over allow
  3. Resource Patterns: Regular expressions can be used to match multiple collections
    db.createRole({
      role: "logAccess",
      privileges: [
        {
          resource: { db: "appDB", collection: /^logs_/ },
          actions: ["find", "insert"]
        }
      ],
      roles: []
    })
    
  4. Authentication Database: The database where a user is created is important and affects the authentication process
  5. Replica Sets and Sharding: In cluster environments, permission management must be consistent across all nodes

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.