在Debian上设置MongoDB的认证与授权,可以按照以下步骤进行:
首先,确保你已经安装了MongoDB。你可以使用以下命令来安装:
sudo apt update
sudo apt install -y mongodb
安装完成后,启动MongoDB服务:
sudo systemctl start mongod
确保MongoDB服务在系统启动时自动启动:
sudo systemctl enable mongod
编辑MongoDB的配置文件 /etc/mongod.conf
,找到 security
部分并启用认证:
security:
authorization: enabled
保存并关闭文件后,重启MongoDB服务以应用更改:
sudo systemctl restart mongod
连接到MongoDB并创建一个管理员用户:
mongo -u admin -p
在MongoDB shell中,创建一个管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
退出MongoDB shell:
exit
使用新创建的管理员用户重新连接到MongoDB:
mongo -u admin -p --authenticationDatabase admin
在MongoDB shell中,创建一个新的数据库用户:
use your_database
db.createUser({
user: "your_user",
pwd: "your_password",
roles: [
{ role: "readWrite", db: "your_database" }
]
})
退出MongoDB shell:
exit
为了增强安全性,你可以配置MongoDB使用TLS/SSL。编辑 /etc/mongod.conf
文件,添加以下内容:
net:
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem
确保你已经生成了SSL证书和密钥文件,并将它们放在指定的路径中。
应用TLS/SSL配置后,重启MongoDB服务:
sudo systemctl restart mongod
使用新创建的用户连接到MongoDB并验证权限:
mongo -u your_user -p --authenticationDatabase your_database
你应该能够成功连接并执行数据库操作。
通过以上步骤,你已经在Debian上成功设置了MongoDB的认证与授权。