在Debian系統上配置MongoDB的認證與授權,可以按照以下步驟進行:
首先,確保你已經安裝了MongoDB。如果沒有安裝,可以使用以下命令進行安裝:
sudo apt update
sudo apt install -y mongodb
啟動MongoDB服務并設置為開機自啟動:
sudo systemctl start mongod
sudo systemctl enable mongod
編輯MongoDB的配置文件 /etc/mongod.conf
,找到 security
部分并啟用認證:
security:
authorization: enabled
保存配置文件后,重啟MongoDB服務以應用更改:
sudo systemctl restart mongod
連接到MongoDB并創建一個管理員用戶。使用以下命令連接到MongoDB:
mongo
在MongoDB shell中,切換到 admin
數據庫并創建管理員用戶:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
退出MongoDB shell并重新連接,這次需要提供用戶名和密碼:
mongo -u admin -p your_password --authenticationDatabase admin
在MongoDB shell中,創建一個新的數據庫用戶并分配角色。例如,創建一個名為 myuser
的用戶,并為其分配 readWrite
角色:
use mydatabase
db.createUser({
user: "myuser",
pwd: "myuser_password",
roles: ["readWrite"]
})
使用新創建的用戶連接到MongoDB:
mongo -u myuser -p myuser_password --authenticationDatabase mydatabase
確保你的防火墻允許MongoDB的默認端口(27017):
sudo ufw allow 27017
最后,驗證配置是否正確。嘗試使用新用戶連接到MongoDB并執行一些操作,例如插入或查詢數據。
通過以上步驟,你已經在Debian系統上成功配置了MongoDB的認證與授權。