下面以 Debian(如 Debian 11 / 12) 为例,说明如何为 MongoDB 设置用户权限(启用鉴权)。
sudo apt update
sudo apt install -y mongodb-org
启动服务:
sudo systemctl enable mongod
sudo systemctl start mongod
MongoDB 默认 不开启鉴权,本地可直接连接:
mongo
或(新版本):
mongosh
⚠️ 生产环境必须先创建管理员用户。
进入 MongoDB:
mongosh
切换到 admin 库:
use admin
创建超级管理员:
db.createUser({
user: "admin",
pwd: "StrongPassword123",
roles: [{ role: "root", db: "admin" }]
})
退出:
exit
编辑配置文件:
sudo nano /etc/mongod.conf
找到 security 部分,修改为:
security:
authorization: enabled
若没有该段,直接添加即可。
重启 MongoDB:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
假设应用使用 mydb:
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword456",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
应用连接字符串示例:
mongodb://appuser:AppPassword456@localhost:27017/mydb
| 角色 | 说明 |
|---|---|
| root | 超级权限 |
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
只允许本地或指定 IP:
sudo ufw allow from 192.168.1.0/24 to any port 27017
--authenticationDatabase如果你需要:
可以直接告诉我。