在 CentOS 上给 MongoDB 开启认证(用户名/密码登录),一般步骤如下:
MongoDB 的配置文件通常位于:
/etc/mongod.conf
编辑配置文件:
vi /etc/mongod.conf
在文件中找到或添加 security 配置:
security:
authorization: enabled
注意:
authorization前面有两个空格缩进,属于security下
保存并退出。
systemctl restart mongod
查看状态:
systemctl status mongod
如果 还没开启认证,先登录 MongoDB:
mongo
切换到 admin 库并创建管理员:
use admin
db.createUser({
user: "admin",
pwd: "yourpassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
退出:
exit
mongo -u admin -p --authenticationDatabase admin
或连接指定库:
mongo -u admin -p yourpassword --authenticationDatabase admin
use mydb
db.createUser({
user: "test",
pwd: "test123",
roles: [{ role: "readWrite", db: "mydb" }]
})
登录:
mongo -u test -p test123 --authenticationDatabase mydb
如果远程连接:
firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
mongod.conf 缩进是否正确(YAML 格式)authorization: enabled如果你用的是 MongoDB 6.x / 7.x(新版本) 或 Docker 安装的 MongoDB,可以告诉我,我给你对应方案。