首先確保Linux系統已安裝MongoDB Community Server。以CentOS為例,可通過以下命令安裝:
sudo yum install mongodb mongodb-server mongodb-devel
安裝完成后,啟動MongoDB服務并設置開機自啟:
sudo systemctl start mongod
sudo systemctl enable mongod
權限管理的核心是啟用身份驗證,需修改MongoDB配置文件(通常位于/etc/mongod.conf):
sudo nano /etc/mongod.conf
找到security section,添加或修改以下內容:
security:
authorization: enabled
保存文件后,重啟MongoDB服務使配置生效:
sudo systemctl restart mongod
為安全起見,首先創建一個管理員用戶(擁有root角色,可管理所有數據庫的用戶和角色):
mongo
在MongoDB shell中執行:
use admin
db.createUser({
user: "admin",
pwd: "StrongAdminPassword123!",
roles: ["root"]
})
exit
注:
root是MongoDB內置的最高權限角色,可管理集群、數據庫、用戶等所有資源。
根據業務需求,為特定數據庫創建用戶并分配最小必要權限(遵循“最小權限原則”):
示例1:創建讀寫權限用戶(適用于應用訪問數據庫)
mongo -u admin -p StrongAdminPassword123 --authenticationDatabase admin
在shell中執行:
use myDatabase // 替換為目標數據庫名
db.createUser({
user: "appUser",
pwd: "AppUserPassword456!",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
exit
示例2:創建只讀權限用戶(適用于報表查詢等場景)
use myDatabase
db.createUser({
user: "reportUser",
pwd: "ReportUserPassword789!",
roles: [{ role: "read", db: "myDatabase" }]
})
exit
常用內置角色說明:
| 角色 | 權限范圍 | 適用場景 |
|---|---|---|
read |
讀取指定數據庫的所有數據 | 報表查詢、數據分析 |
readWrite |
讀寫指定數據庫的所有數據 | 應用程序日常數據操作 |
dbAdmin |
數據庫管理(索引、統計等) | 數據庫維護人員 |
userAdmin |
管理指定數據庫的用戶/角色 | 數據庫管理員(僅限該數據庫) |
root |
超級權限(所有數據庫、集群) | 系統管理員 |
| 更多角色可參考MongoDB官方文檔。 |
使用創建的用戶連接MongoDB,驗證其權限是否生效:
驗證讀寫用戶:
mongo -u appUser -p AppUserPassword456 --authenticationDatabase myDatabase
在shell中執行:
use myDatabase
db.mycollection.insert({ name: "test" }) // 測試寫入
db.mycollection.find() // 測試讀取
exit
驗證只讀用戶:
mongo -u reportUser -p ReportUserPassword789 --authenticationDatabase myDatabase
在shell中執行:
use myDatabase
db.mycollection.find() // 應能讀取數據
db.mycollection.insert({ name: "test" }) // 應提示無寫入權限
exit
使用TLS/SSL加密連接:在/etc/mongod.conf中配置SSL,防止數據傳輸被竊聽:
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem
重啟服務后,客戶端連接需指定SSL參數:
mongo --ssl --sslCAFile /path/to/ca.pem --sslPEMKeyFile /path/to/mongodb.pem -u appUser -p AppUserPassword456 --authenticationDatabase myDatabase
使用防火墻限制訪問:通過ufw限制MongoDB端口(默認27017)的訪問,僅允許可信IP訪問:
sudo ufw allow from 192.168.1.100 to any port 27017
sudo ufw enable
通過以上步驟,可在Linux系統上完成MongoDB的權限管理,確保數據庫的安全性和數據的完整性。