文章目录
MongoDB 用户管理
1. 连接到 MongoDB
在开始管理用户之前,首先需要连接到 MongoDB 实例:
# 连接到本地 MongoDB 实例
mongo
# 或者连接到远程实例
mongo --host <hostname> --port <port> -u <username> -p <password>
2. 用户创建
2.1 创建管理员用户
最大权限
mongos> use admin
mongos> db.createUser({user: "admin", pwd: "admin123", roles: ["root"]})
首先创建一个具有用户管理权限的管理员账户:
// 切换到 admin 数据库
use admin
// 创建管理员用户
db.createUser({
user: "adminUser",
pwd: "securePassword123", // 实际使用时请设置更复杂的密码
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
2.2 创建特定数据库用户
为特定数据库创建用户:
// 切换到目标数据库
use myDatabase
// 创建具有读写权限的用户
db.createUser({
user: "appUser",
pwd: "appPassword123",
roles: [
{ role: "readWrite", db: "myDatabase" },
{ role: "dbAdmin", db: "myDatabase" }
]
})
2.3 常用内置角色
read
: 只读权限readWrite
: 读写权限dbAdmin
: 数据库管理权限userAdmin
: 用户管理权限clusterAdmin
: 集群管理权限(仅admin数据库)dbOwner
: 数据库所有者(包含readWrite, dbAdmin和userAdmin权限)
3. 用户管理操作
3.1 查看所有用户
use admin
db.system.users.find()
3.2 查看特定用户信息
db.getUser("appUser")
3.3 更新用户密码
db.updateUser("appUser", {
pwd: "newSecurePassword456"
})
3.4 添加用户角色
db.grantRolesToUser("appUser", [
{ role: "read", db: "anotherDatabase" }
])
3.5 移除用户角色
db.revokeRolesFromUser("appUser", [
{ role: "read", db: "anotherDatabase" }
])
3.6 删除用户
db.dropUser("appUser")
4. 权限修改
4.1 创建自定义角色
use admin
db.createRole({
role: "customAppRole",
privileges: [
{
resource: { db: "myDatabase", collection: "customers" },
actions: ["find", "insert", "update"]
},
{
resource: { db: "myDatabase", collection: "orders" },
actions: ["find"]
}
],
roles: []
})
4.2 将自定义角色分配给用户
db.grantRolesToUser("appUser", ["customAppRole"])
5. 启用身份验证
要使用户管理生效,需要在 MongoDB 配置中启用身份验证:
- 编辑 MongoDB 配置文件(通常位于
/etc/mongod.conf
) - 添加或修改以下部分:
security:
authorization: enabled
- 重启 MongoDB 服务:
sudo systemctl restart mongod
6. 允许远程连接
6.1 修改绑定IP
- 编辑 MongoDB 配置文件:
net:
port: 27017
bindIp: 0.0.0.0 # 允许所有IP连接,或指定特定IP
- 重启 MongoDB 服务
6.2 防火墙设置
如果服务器有防火墙,需要开放 MongoDB 端口(默认27017):
sudo ufw allow 27017
6.3 安全注意事项
允许远程连接时,务必:
- 使用强密码
- 考虑设置网络层面的访问控制(如IP白名单)
- 启用TLS/SSL加密连接
- 限制用户权限到最小必要范围
7. 使用认证连接
启用认证后,连接时需要提供凭据:
mongo -u "appUser" -p "appPassword123" --authenticationDatabase "myDatabase"
或者在连接字符串中:
mongo "mongodb://appUser:appPassword123@localhost:27017/myDatabase"
8. 最佳实践
- 遵循最小权限原则,只授予用户必要的权限
- 定期审计用户和权限
- 使用复杂的密码并定期更换
- 生产环境考虑启用TLS/SSL加密
- 对于重要操作,考虑使用审计日志
9. 常见问题解决
9.1 忘记管理员密码
- 暂时关闭认证(修改配置文件,去掉authorization: enabled)
- 重启 MongoDB
- 连接到无认证的实例
- 重置管理员密码
- 重新启用认证并重启
9.2 连接被拒绝
- 检查 MongoDB 服务是否运行
- 检查防火墙设置
- 验证绑定IP配置
- 检查认证凭据是否正确