在 CentOS 上给 MongoDB 做授权(开启用户认证 + 创建用户),一般按下面步骤来。
vim /etc/mongod.conf
security 配置项,改为如下内容security:
改成:
security:
authorization: enabled
如果是 CentOS 上默认 yum 安装的 MongoDB,配置一般是 YAML 格式,注意缩进。
systemctl restart mongod
mongo
use admin
db.createUser({
user: "root",
pwd: "yourpassword",
roles: [ { role: "root", db: "admin" } ]
})
mongo -u root -p yourpassword --authenticationDatabase admin
例如给 testdb 建一个读写用户:
use testdb
db.createUser({
user: "testuser",
pwd: "testpass",
roles: [ "readWrite" ]
})
登录方式:
mongo -u testuser -p testpass --authenticationDatabase testdb
| 角色 | 说明 |
|---|---|
root |
超级管理员 |
read |
只读 |
readWrite |
读写 |
dbAdmin |
数据库管理 |
userAdmin |
用户管理 |
检查 /etc/mongod.conf 缩进是否正确(YAML 对空格敏感)
authorizationuse admin
db.changeUserPassword("root", "newpass")
如果你用的是 MongoDB 6.x / 7.x(systemd + mongosh),或者 Docker 版 MongoDB,可以告诉我,我给你对应版本的操作。