在 Debian 上给 MongoDB 设置权限,通常包含 两步:
1️⃣ 启用鉴权(auth)
2️⃣ 创建用户并分配角色
下面以 MongoDB 6.x / 7.x(apt 安装) 为例说明。
编辑 MongoDB 配置文件:
sudo nano /etc/mongod.conf
在文件中找到 security 部分,改为:
security:
authorization: enabled
如果原本没有 security,直接添加即可。
sudo systemctl restart mongod
在未启用 auth 前或启用后第一次连接 localhost 时操作。
mongosh
切换到 admin 库:
use admin
创建管理员:
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [{ role: "root", db: "admin" }]
})
退出:
quit
mongosh -u admin -p --authenticationDatabase admin
例如创建 mydb 的读写用户:
use mydb
db.createUser({
user: "myuser",
pwd: "UserPassword",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
连接示例:
mongosh -u myuser -p --authenticationDatabase mydb
| 角色 | 权限 |
|---|---|
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
| root | 超级管理员 |
如果只允许本地访问:
sudo ufw deny 27017
sudo ufw allow from 127.0.0.1 to any port 27017
authorizationbindIp如果你愿意,我可以:
直接告诉我你的使用场景即可。