在Linux系統中,MongoDB的權限可以通過以下步驟進行設置:
首先,你需要創建一個用戶并為其分配適當的角色。MongoDB使用基于角色的訪問控制(RBAC)。
mongo
shell創建用戶mongo
在mongo
shell中執行以下命令:
use admin
db.createUser({
user: "myUserAdmin",
pwd: "myUserAdminPwd",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
mongosh
shell創建用戶(MongoDB 4.0及以上版本)mongosh
在mongosh
shell中執行以下命令:
use admin
db.createUser({
user: "myUserAdmin",
pwd: "myUserAdminPwd",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
編輯MongoDB配置文件(通常是/etc/mongod.conf
),確保啟用了身份驗證:
security:
authorization: enabled
使配置更改生效:
sudo systemctl restart mongod
使用新創建的用戶連接到MongoDB:
mongo -u myUserAdmin -p myUserAdminPwd --authenticationDatabase admin
如果你需要為特定數據庫創建用戶,可以在目標數據庫中創建用戶并分配角色。
mongo
shell中創建數據庫級別的用戶use myDatabase
db.createUser({
user: "myAppUser",
pwd: "myAppUserPwd",
roles: [
{ role: "readWrite", db: "myDatabase" }
]
})
你可以使用db.runCommand
來驗證用戶的權限:
db.runCommand({ connectionStatus: 1 })
為了提高安全性,可以配置MongoDB使用TLS/SSL加密連接。這需要在MongoDB配置文件中進行相應的設置,并確??蛻舳艘仓С諸LS/SSL。
mongod.conf
中啟用TLS/SSLnet:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem
mongo --ssl --sslCAFile /path/to/ca.pem --sslPEMKeyFile /path/to/mongodb.pem -u myUserAdmin -p myUserAdminPwd --authenticationDatabase admin
通過以上步驟,你可以在Linux系統中為MongoDB設置詳細的權限和安全性配置。