MongoDB用户权限管理 #

一、认证概述 #

1.1 认证机制 #

MongoDB支持多种认证机制:

机制 说明
SCRAM 默认机制,用户名密码认证
x.509 证书认证
LDAP LDAP认证(企业版)
Kerberos Kerberos认证(企业版)

1.2 启用认证 #

yaml
# mongod.conf
security:
  authorization: enabled
bash
# 命令行启动
mongod --auth

1.3 认证数据库 #

数据库 说明
admin 管理用户和角色
local 本地数据库
用户数据库 用户定义的数据库

二、用户管理 #

2.1 创建管理员 #

javascript
// 连接MongoDB
mongosh

// 切换到admin数据库
use admin

// 创建管理员
db.createUser({
    user: "admin",
    pwd: "password123",
    roles: [
        { role: "userAdminAnyDatabase", db: "admin" },
        { role: "readWriteAnyDatabase", db: "admin" }
    ]
})

// 或创建超级管理员
db.createUser({
    user: "root",
    pwd: "password123",
    roles: ["root"]
})

2.2 创建应用用户 #

javascript
// 切换到目标数据库
use mydb

// 创建读写用户
db.createUser({
    user: "appuser",
    pwd: "password123",
    roles: [
        { role: "readWrite", db: "mydb" }
    ]
})

// 创建只读用户
db.createUser({
    user: "readonly",
    pwd: "password123",
    roles: [
        { role: "read", db: "mydb" }
    ]
})

2.3 查看用户 #

javascript
// 查看当前数据库用户
db.getUsers()

// 查看指定用户
db.getUser("appuser")

// 查看所有用户(admin数据库)
use admin
db.system.users.find()

2.4 修改用户 #

javascript
// 修改密码
db.changeUserPassword("appuser", "newpassword")

// 修改用户信息
db.updateUser("appuser", {
    roles: [
        { role: "readWrite", db: "mydb" },
        { role: "read", db: "otherdb" }
    ]
})

// 添加角色
db.grantRolesToUser("appuser", [
    { role: "dbAdmin", db: "mydb" }
])

// 移除角色
db.revokeRolesFromUser("appuser", [
    { role: "read", db: "otherdb" }
])

2.5 删除用户 #

javascript
// 删除用户
db.dropUser("appuser")

// 删除所有用户(当前数据库)
db.dropAllUsers()

三、角色管理 #

3.1 内置角色 #

数据库用户角色

角色 说明
read 读取数据
readWrite 读写数据

数据库管理角色

角色 说明
dbAdmin 数据库管理
dbOwner 数据库所有者
userAdmin 用户管理

集群管理角色

角色 说明
clusterAdmin 集群管理
clusterManager 集群监控和管理
clusterMonitor 集群监控
hostManager 主机管理

备份恢复角色

角色 说明
backup 备份
restore 恢复

全局角色

角色 说明
readAnyDatabase 读取任意数据库
readWriteAnyDatabase 读写任意数据库
userAdminAnyDatabase 管理任意数据库用户
dbAdminAnyDatabase 管理任意数据库
root 超级管理员

3.2 创建自定义角色 #

javascript
// 创建自定义角色
use admin

db.createRole({
    role: "appAdmin",
    privileges: [
        { resource: { db: "mydb", collection: "" }, actions: ["find", "insert", "update"] },
        { resource: { db: "mydb", collection: "logs" }, actions: ["insert"] }
    ],
    roles: [
        { role: "read", db: "mydb" }
    ]
})

3.3 查看角色 #

javascript
// 查看角色
db.getRole("appAdmin", { showPrivileges: true })

// 查看所有角色
db.getRoles()

// 查看用户角色
db.getUser("appuser").roles

3.4 修改角色 #

javascript
// 添加权限
db.grantPrivilegesToRole("appAdmin", [
    { resource: { db: "mydb", collection: "users" }, actions: ["remove"] }
])

// 移除权限
db.revokePrivilegesFromRole("appAdmin", [
    { resource: { db: "mydb", collection: "users" }, actions: ["remove"] }
])

// 添加角色
db.grantRolesToRole("appAdmin", [
    { role: "readWrite", db: "mydb" }
])

// 删除角色
db.dropRole("appAdmin")

四、权限操作 #

4.1 权限操作类型 #

操作类型 说明
find 查询
insert 插入
update 更新
remove 删除
createCollection 创建集合
dropCollection 删除集合
createIndex 创建索引
dropIndex 删除索引

4.2 资源定义 #

javascript
// 指定数据库和集合
{ resource: { db: "mydb", collection: "users" }, actions: ["find"] }

// 指定数据库所有集合
{ resource: { db: "mydb", collection: "" }, actions: ["find"] }

// 所有数据库所有集合
{ resource: { db: "", collection: "" }, actions: ["find"] }

// 集群资源
{ resource: { cluster: true }, actions: ["serverStatus"] }

五、认证连接 #

5.1 命令行认证 #

bash
# 连接时认证
mongosh -u admin -p password123 --authenticationDatabase admin

# 连接后认证
mongosh
> use admin
> db.auth("admin", "password123")

5.2 连接字符串认证 #

bash
# 连接字符串
mongosh "mongodb://admin:password123@localhost:27017/mydb?authSource=admin"

# MongoDB Atlas
mongosh "mongodb+srv://user:password@cluster.mongodb.net/mydb"

5.3 程序连接 #

javascript
// Node.js
const { MongoClient } = require('mongodb')

const uri = "mongodb://admin:password123@localhost:27017/mydb?authSource=admin"
const client = new MongoClient(uri)

async function run() {
    await client.connect()
    const db = client.db('mydb')
    // ...
}

六、复制集认证 #

6.1 配置keyFile #

bash
# 生成keyFile
openssl rand -base64 756 > /etc/mongodb/keyfile
chmod 400 /etc/mongodb/keyfile
chown mongodb:mongodb /etc/mongodb/keyfile
yaml
# mongod.conf
security:
  authorization: enabled
  keyFile: /etc/mongodb/keyfile

6.2 复制集认证流程 #

text
1. 生成keyFile
2. 分发keyFile到所有成员
3. 配置所有成员使用keyFile
4. 重启所有成员
5. 创建管理员用户

七、分片集群认证 #

7.1 配置认证 #

yaml
# 所有组件使用相同的keyFile
security:
  keyFile: /etc/mongodb/keyfile

7.2 分片集群认证配置 #

text
1. Config Server配置keyFile
2. 所有Shard配置keyFile
3. mongos配置keyFile
4. 创建管理员用户

八、最佳实践 #

8.1 用户管理建议 #

text
1. 最小权限原则
   - 只授予必要的权限
   - 避免使用root角色

2. 分类管理
   - 管理员用户
   - 应用用户
   - 只读用户

3. 密码管理
   - 使用强密码
   - 定期更换密码
   - 不在代码中硬编码

4. 审计日志
   - 启用审计日志
   - 记录用户操作

8.2 安全配置 #

yaml
# mongod.conf
security:
  authorization: enabled
  keyFile: /etc/mongodb/keyfile

net:
  bindIp: 127.0.0.1,内网IP
  port: 27017

# 启用TLS
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/server.pem

8.3 审计配置 #

yaml
# mongod.conf
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json

九、总结 #

用户管理操作速查表:

操作 命令
创建用户 db.createUser({…})
查看用户 db.getUsers()
修改密码 db.changeUserPassword(“user”, “pwd”)
删除用户 db.dropUser(“user”)
认证 db.auth(“user”, “pwd”)

常用角色:

角色 说明
read 只读
readWrite 读写
dbAdmin 数据库管理
userAdmin 用户管理
root 超级管理员

下一步,让我们学习备份与恢复!

最后更新:2026-03-27