在Debian系统上配置MongoDB的认证与授权,可以按照以下步骤进行:
首先,确保你已经安装了MongoDB。如果没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install -y mongodb
启动MongoDB服务并设置为开机自启动:
sudo systemctl start mongod
sudo systemctl enable mongod
编辑MongoDB的配置文件 /etc/mongod.conf
,找到 security
部分并启用认证:
security:
authorization: enabled
保存配置文件后,重启MongoDB服务以应用更改:
sudo systemctl restart mongod
连接到MongoDB并创建一个管理员用户。使用以下命令连接到MongoDB:
mongo
在MongoDB shell中,切换到 admin
数据库并创建管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
退出MongoDB shell并重新连接,这次需要提供用户名和密码:
mongo -u admin -p your_password --authenticationDatabase admin
在MongoDB shell中,创建一个新的数据库用户并分配角色。例如,创建一个名为 myuser
的用户,并为其分配 readWrite
角色:
use mydatabase
db.createUser({
user: "myuser",
pwd: "myuser_password",
roles: ["readWrite"]
})
使用新创建的用户连接到MongoDB:
mongo -u myuser -p myuser_password --authenticationDatabase mydatabase
确保你的防火墙允许MongoDB的默认端口(27017):
sudo ufw allow 27017
最后,验证配置是否正确。尝试使用新用户连接到MongoDB并执行一些操作,例如插入或查询数据。
通过以上步骤,你已经在Debian系统上成功配置了MongoDB的认证与授权。