在linux系統中,可以按照以下步驟對mongodb進行權限配置:
1. 創建用戶與角色
首先創建一個用戶,并為其分配合適的角色。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環境中運行以下命令:
use admin db.createUser({ user: "myUserAdmin", pwd: "myUserAdminPwd", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" } ] })
2. 啟用身份驗證功能
修改MongoDB的配置文件(通常位于/etc/mongod.conf),確保開啟身份驗證支持:
security: authorization: enabled
3. 重啟MongoDB服務
應用配置變更:
sudo systemctl restart mongod
4. 通過新用戶連接MongoDB
使用新建的用戶信息連接數據庫:
mongo -u myUserAdmin -p myUserAdminPwd --authenticationDatabase admin
5. 創建特定數據庫級別的用戶和角色
如果需要為某個具體數據庫設置用戶,則可在對應數據庫中添加用戶并指定其角色。
在mongo shell中創建數據庫級別用戶
use myDatabase db.createUser({ user: "myAppUser", pwd: "myAppUserPwd", roles: [ { role: "readWrite", db: "myDatabase" } ] })
6. 檢查用戶權限
可以通過db.runCommand命令檢查用戶的權限狀態:
db.runCommand({ connectionStatus: 1 })
7. 配置TLS/ssl加密連接(可選)
為了增強安全性,可以選擇啟用TLS/SSL來加密通信。這需要在mongod.conf中進行相關配置,并且客戶端也需具備TLS/SSL支持。
在mongod.conf中啟用TLS/SSL支持
net: ssl: mode: requireSSL PEMKeyFile: /path/to/mongodb.pem CAFile: /path/to/ca.pem
客戶端連接時啟用TLS/SSL
mongo --ssl --sslCAFile /path/to/ca.pem --sslPEMKeyFile /path/to/mongodb.pem -u myUserAdmin -p myUserAdminPwd --authenticationDatabase admin
通過上述操作,即可完成Linux環境下MongoDB的權限管理及安全策略的設定。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END