在Ubuntu上配置MongoDB的认证与授权,可以按照以下步骤进行:
首先,确保你已经安装了MongoDB。如果没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install -y mongodb
安装完成后,启动MongoDB服务:
sudo systemctl start mongod
确保MongoDB服务正在运行:
sudo systemctl status mongod
默认情况下,MongoDB在Ubuntu上是没有启用认证的。你需要修改MongoDB的配置文件来启用认证。
编辑MongoDB配置文件 /etc/mongod.conf:
sudo nano /etc/mongod.conf
找到 security 部分,并进行如下修改:
security:
authorization: enabled
保存并退出编辑器。
为了使配置生效,需要重启MongoDB服务:
sudo systemctl restart mongod
连接到MongoDB shell:
mongo
在MongoDB shell中,创建一个管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
将 your_password 替换为你想要设置的密码。
退出MongoDB shell并重新连接,使用新创建的管理员用户:
mongo -u admin -p your_password --authenticationDatabase admin
现在你可以创建新的数据库和用户,并为其分配角色。例如,创建一个名为 mydatabase 的数据库,并为其创建一个用户:
use mydatabase
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: ["readWrite", "dbOwner"]
})
将 myuser 和 mypassword 替换为你想要设置的用户名和密码。
退出MongoDB shell并重新连接,使用新创建的用户:
mongo -u myuser -p mypassword --authenticationDatabase mydatabase
在MongoDB shell中,验证新用户的权限:
use mydatabase
db.runCommand({ connectionStatus: 1 })
你应该能够看到新用户的权限信息。
通过以上步骤,你已经在Ubuntu上成功配置了MongoDB的认证与授权。