User Management and Access Control
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 databasereadWrite
: Includesread
permissions and allows writing datadbAdmin
: Can perform administrative operations, such as index creation and statistics collectionuserAdmin
: Can create and modify users and roles for the database
Cluster Administration Roles
clusterAdmin
: Highest cluster administration privilegesclusterManager
: Monitors and manages the clusterclusterMonitor
: Read-only cluster monitoring privilegeshostManager
: Monitors and manages servers
Backup and Restoration Roles
backup
: Permissions for backing up datarestore
: Permissions for restoring data
All-Database Roles
readAnyDatabase
: Read access to all databasesreadWriteAnyDatabase
: Read and write access to all databasesuserAdminAnyDatabase
: Manage users for all databasesdbAdminAnyDatabase
: 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:
- SCRAM-SHA-1/SHA-256 (default)
- x.509 certificate authentication
- LDAP proxy authentication
- 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
- Follow the principle of least privilege
- Regularly rotate credentials
- Use TLS for encrypted connections
- Limit network exposure
- Enable audit logging
- Regularly review user permissions
Common Issue Solutions
Issue 1: Forgotten Administrator Password
- Restart the mongod instance without enabling access control
- Connect to the instance and create a new administrator
- 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
- Avoid excessive role nesting
- Regularly clean up unused users
- Monitor authentication operation performance
- 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
下一篇:加密传输(TLS/SSL)