在 Debian 上部署 MongoDB 后,默认是**不开启鉴权(auth)**的,任何本地连接都可以直接操作数据库。要启用鉴权,一般步骤如下:
以 MongoDB 6.x / 7.x 为例(使用官方源):
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable mongod
sudo systemctl start mongod
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [{ role: "root", db: "admin" }]
})
退出:
quit()
编辑配置文件:
sudo vim /etc/mongod.conf
在文件中添加或修改:
security:
authorization: enabled
注意 YAML 缩进(2 个空格)
重启 MongoDB:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
use admin
db.auth("admin", "StrongPassword")
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [{ role: "readWrite", db: "mydb" }]
})
应用连接串示例:
mongodb://appuser:AppPassword@localhost:27017/mydb
如果远程访问,修改:
net:
bindIp: 0.0.0.0
⚠️ 公网暴露务必配合防火墙 + 鉴权
authorizationuse admin
db.getUsers()
✅ 启用鉴权
✅ 不使用 root 账号连业务库
✅ 强密码
✅ 限制 bindIp
✅ 启用防火墙(ufw / iptables)
如果你需要:
可以继续问我。