在Ubuntu上配置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中,创建一个管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
退出MongoDB shell并重新连接到MongoDB,这次使用新创建的管理员用户进行认证:
mongo -u admin -p your_password --authenticationDatabase admin
你可以根据需要创建其他用户和角色。例如,创建一个只读用户:
use your_database
db.createUser({
user: "readonly_user",
pwd: "readonly_password",
roles: ["read"]
})
为了提高安全性,你可以配置MongoDB以使用SSL/TLS。编辑 /etc/mongod.conf 文件,添加以下内容:
net:
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem
然后重启MongoDB服务:
sudo systemctl restart mongod
确保所有配置都正确无误。你可以尝试使用新创建的用户连接到数据库:
mongo -u readonly_user -p readonly_password --authenticationDatabase your_database
如果一切配置正确,你应该能够成功连接到数据库。
通过以上步骤,你已经在Ubuntu上成功配置了MongoDB的认证。