在CentOS上配置MongoDB认证涉及几个步骤,包括启用认证、创建管理员用户、配置MongoDB服务以及重启服务。以下是详细的步骤:
首先,你需要编辑MongoDB的配置文件/etc/mongod.conf
,启用认证。
sudo vi /etc/mongod.conf
找到并修改以下行:
security:
authorization: enabled
保存并退出编辑器。
接下来,你需要创建一个管理员用户。首先,启动MongoDB服务(如果它还没有运行):
sudo systemctl start mongod
然后,连接到MongoDB shell:
mongo
在MongoDB shell中,创建一个管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
将your_password
替换为你选择的强密码。
为了使更改生效,你需要重新启动MongoDB服务:
sudo systemctl restart mongod
现在,你可以使用管理员用户连接到MongoDB:
mongo -u admin -p your_password --authenticationDatabase admin
你可以为其他数据库创建用户,并分配适当的角色。例如,创建一个名为mydb
数据库的用户:
use mydb
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: ["readWrite", "dbOwner"]
})
将myuser
和mypassword
替换为你选择的用户名和密码。
你可以验证用户的权限:
db.runCommand({ connectionStatus: 1 })
这将显示当前连接的用户信息。
确保你的防火墙允许MongoDB的默认端口(27017):
sudo firewall-cmd --permanent --zone=public --add-port=27017/tcp
sudo firewall-cmd --reload
如果你的系统启用了SELinux,你可能需要配置它以允许MongoDB运行:
sudo setsebool -P mongod_can_network on
通过以上步骤,你应该能够在CentOS上成功配置MongoDB认证。