在Linux系统上为MongoDB设置权限时,需要关注以下几个要点:
安装MongoDB: 确保MongoDB已经安装在您的Linux系统上。如果尚未安装,可以从MongoDB官方网站下载并安装适用于您的Linux发行版的MongoDB Community Server。
创建MongoDB用户:
mongo
use myDatabase
db.createUser({
user: "myUser",
pwd: "myUserPassword",
roles: [
{ role: "readWrite", db: "myDatabase" }
]
})
将myDatabase
替换为您要授权的数据库名称,将myUser
和myUserPassword
替换为您选择的用户名和密码。启用身份验证:
/etc/mongod.conf
),在security
部分下添加或修改以下行以启用身份验证:security:
authorization: enabled
sudo systemctl restart mongod
使用新创建的用户登录:
mongo -u myUser -p myUserPassword --authenticationDatabase myDatabase
这将使用您在第2步中创建的用户凭据登录到MongoDB。创建管理员用户:
admin
数据库并创建一个管理员用户:use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: [root]
})
创建数据库和集合:
use admin
db.createRole({
role: "readOnlyRole",
privileges: [
{
resource: { db: "mydatabase", collection: "" },
actions: [find]
}
],
roles: []
})
use mydatabase
db.createUser({
user: "readOnlyUser",
pwd: "user_password",
roles: [readOnlyRole]
})
验证权限:
mongo -u readOnlyUser -p user_password --authenticationDatabase mydatabase
db.mycollection.find()
使用SSL/TLS加密连接(可选):
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem
sudo systemctl restart mongod
使用防火墙限制访问(可选):
sudo ufw allow 27017/tcp
通过以上步骤,您可以在Linux系统中为MongoDB设置权限,确保数据库的安全性和数据的完整性。