在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并创建一个管理员用户。你可以使用 mongo
shell 连接到MongoDB:
mongo
在 mongo
shell 中,切换到 admin
数据库并创建管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
使用新创建的管理员用户重新连接到MongoDB:
mongo -u admin -p your_password --authenticationDatabase admin
在 mongo
shell 中,切换到你想要创建用户的数据库,并创建一个新用户:
use your_database
db.createUser({
user: "your_user",
pwd: "your_password",
roles: ["readWrite", "dbOwner"]
})
使用新创建的用户连接到MongoDB:
mongo -u your_user -p your_password --authenticationDatabase your_database
确保你的防火墙允许MongoDB的默认端口(27017):
sudo ufw allow 27017
最后,验证认证是否正常工作。尝试在没有密码的情况下连接到MongoDB:
mongo -u your_user -p your_password --authenticationDatabase your_database
如果认证成功,你应该能够连接到MongoDB。
通过以上步骤,你已经在Ubuntu上成功设置了MongoDB的安全认证。