阿里云主机折上折
  • 微信号
Current Site:Index > User Management and Access Control

User Management and Access Control

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

Basic Concepts of User Management

In MongoDB, user management is implemented through Role-Based Access Control (RBAC). Each user is assigned one or more roles, which define the user's permissions to operate on database resources. User account information is stored in the system.users collection of the admin database.

The basic syntax for creating a user is as follows:

db.createUser({
  user: "username",
  pwd: "password",
  roles: [
    { role: "read", db: "reporting" },
    { role: "readWrite", db: "products" }
  ]
})

Detailed Explanation of Built-in Roles

MongoDB provides various built-in roles, mainly categorized as follows:

Database User Roles

  • read: Allows reading data from the specified database
  • readWrite: Includes read permissions and allows writing data
  • dbAdmin: Can perform administrative operations, such as index creation and statistics collection
  • userAdmin: Can create and modify users and roles for the database

Cluster Administration Roles

  • clusterAdmin: Highest cluster administration privileges
  • clusterManager: Monitors and manages the cluster
  • clusterMonitor: Read-only cluster monitoring privileges
  • hostManager: Monitors and manages servers

Backup and Restoration Roles

  • backup: Permissions for backing up data
  • restore: Permissions for restoring data

All-Database Roles

  • readAnyDatabase: Read access to all databases
  • readWriteAnyDatabase: Read and write access to all databases
  • userAdminAnyDatabase: Manage users for all databases
  • dbAdminAnyDatabase: Administer all databases

Creating Custom Roles

When built-in roles do not meet requirements, custom roles can be created:

db.createRole({
  role: "manageProducts",
  privileges: [
    {
      resource: { db: "inventory", collection: "products" },
      actions: [ "find", "update", "insert", "remove" ]
    },
    {
      resource: { db: "inventory", collection: "categories" },
      actions: [ "find" ]
    }
  ],
  roles: []
})

Permission Inheritance and Combination

Roles can inherit permissions from other roles:

db.createRole({
  role: "supervisor",
  privileges: [],
  roles: ["readWrite", "dbAdmin"]
})

User Authentication Methods

MongoDB supports multiple authentication mechanisms:

  1. SCRAM-SHA-1/SHA-256 (default)
  2. x.509 certificate authentication
  3. LDAP proxy authentication
  4. Kerberos authentication

To enable authentication, set the following in the configuration file:

security:
  authorization: enabled

Access Control Practical Examples

Application Connection Example

Node.js connection authentication example:

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

async function connect() {
  const client = new MongoClient('mongodb://username:password@localhost:27017/admin', {
    authSource: 'admin',
    authMechanism: 'SCRAM-SHA-256'
  });
  
  try {
    await client.connect();
    const db = client.db('products');
    // Perform operations...
  } finally {
    await client.close();
  }
}

Sharded Cluster Access Control

In a sharded cluster, access control must be enabled on all mongos and mongod instances:

// Create an administrator on the config server
db.getSiblingDB("admin").createUser({
  user: "clusterAdmin",
  pwd: "securePassword",
  roles: [ { role: "clusterAdmin", db: "admin" } ]
})

Auditing and Monitoring

MongoDB provides auditing functionality to record user actions:

auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{ "users": { $elemMatch: { "user": "admin" } } }'

Best Security Practices

  1. Follow the principle of least privilege
  2. Regularly rotate credentials
  3. Use TLS for encrypted connections
  4. Limit network exposure
  5. Enable audit logging
  6. Regularly review user permissions

Common Issue Solutions

Issue 1: Forgotten Administrator Password

  1. Restart the mongod instance without enabling access control
  2. Connect to the instance and create a new administrator
  3. Restart the instance with access control enabled
mongod --dbpath /data/db --noauth

Issue 2: Insufficient Privileges Error

Check current user permissions:

db.runCommand({ connectionStatus: 1 })

Issue 3: Cross-Database Access

Explicitly specify the authentication database:

db.auth("username", "password", { mechanism: "SCRAM-SHA-256" })

Advanced Access Control Scenarios

Field-Level Access Control

Use views to implement field-level access control:

db.createView(
  "restrictedUserView",
  "users",
  [ { $project: { name: 1, email: 1, _id: 0 } } ]
)

Time-Restricted Access

Combine custom roles with application logic:

// Application checks time
function checkAccessTime(user) {
  const now = new Date();
  const hours = now.getHours();
  return hours >= 9 && hours < 17;
}

Performance Considerations

  1. Avoid excessive role nesting
  2. Regularly clean up unused users
  3. Monitor authentication operation performance
  4. Consider using connection pools to reduce authentication overhead

Integration with Other Systems

LDAP Integration Configuration

security:
  ldap:
    servers: "ldap.example.com"
    transportSecurity: tls
    authz:
      queryTemplate: "ou=users,dc=example,dc=com??sub?(uid={USER})"
  authorization: enabled

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.