在 CentOS 上给 MongoDB 开启认证(用户名/密码登录),一般步骤如下:
MongoDB 的配置文件通常是:
/etc/mongod.conf
用 vim 编辑:
vim /etc/mongod.conf
在文件中添加或确认以下内容(注意缩进,YAML 格式严格):
security:
authorization: enabled
如果是老版本(2.6 之前),可能是:
auth = true
systemctl restart mongod
查看状态:
systemctl status mongod
在开启认证前或刚开启后,必须有一个管理员账号,否则无法管理。
mongo
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
mongo -u admin -p --authenticationDatabase admin
use admin
db.auth("admin","YourStrongPassword")
use testdb
db.createUser({
user: "testuser",
pwd: "testpass",
roles: [ { role: "readWrite", db: "testdb" } ]
})
如果远程连接:
firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
未认证时执行:
show dbs
应报错 not authorized
root / readWrite / read如果你用的是 MongoDB 4.x / 5.x / 6.x 或 Docker 版,可以告诉我,我可以给你对应版本的具体命令。