在 Linux 上配置 MongoDB 认证,通常分为 启用访问控制 和 创建用户 两个步骤。下面以 MongoDB 4.x / 5.x / 6.x 为例说明(社区版)。
MongoDB 的配置文件一般在:
/etc/mongod.conf
编辑配置文件:
sudo vim /etc/mongod.conf
在 security 节点下添加:
security:
authorization: enabled
如果是旧版本(2.6 之前)可能用
auth = true,但新版本必须用 YAML 格式。
⚠️ 重要:
在开启 authorization: enabled 之前,必须先有一个管理员用户,否则无法登录。
如果已经开启认证但没用户,可暂时注释掉:
# security:
# authorization: enabled
然后重启 MongoDB:
sudo systemctl restart mongod
mongo
# 或(新版)
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [{ role: "root", db: "admin" }]
})
编辑配置文件:
security:
authorization: enabled
重启 MongoDB:
sudo systemctl restart mongod
mongo -u admin -p --authenticationDatabase admin
或:
mongosh "mongodb://admin:StrongPassword@localhost:27017/admin"
use admin
db.auth("admin", "StrongPassword")
不要所有业务都用 admin 用户。
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
登录方式:
mongo -u appuser -p --authenticationDatabase mydb
尝试无账号连接:
mongo
执行:
show dbs
如果提示 not authorized,说明认证已生效 ✅
--noauth 启动sudo ufw allow 27017
如果你需要:
可以继续问我。