在CentOS上配置MongoDB認證,可以按照以下步驟進行:
首先,確保你已經安裝了MongoDB。如果還沒有安裝,可以使用以下命令進行安裝:
sudo yum install -y mongodb-org
安裝完成后,啟動MongoDB服務:
sudo systemctl start mongod
并設置開機自啟動:
sudo systemctl enable mongod
MongoDB的認證配置文件通常是/etc/mongod.conf
。你需要編輯這個文件來啟用認證。
打開配置文件:
sudo vi /etc/mongod.conf
在security
部分添加或修改以下內容:
security:
authorization: enabled
保存并退出編輯器。
為了使配置生效,需要重啟MongoDB服務:
sudo systemctl restart mongod
連接到MongoDB并創建一個管理員用戶:
mongo -u admin -p your_password --authenticationDatabase admin
在MongoDB shell中執行以下命令創建管理員用戶:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
退出當前MongoDB shell并使用新創建的管理員用戶重新連接:
mongo -u admin -p your_password --authenticationDatabase admin
現在你可以為其他數據庫創建用戶。例如,為mydatabase
數據庫創建一個用戶:
use mydatabase
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: ["readWrite", "dbOwner"]
})
你可以使用新創建的用戶連接到數據庫并驗證其權限:
mongo -u myuser -p mypassword --authenticationDatabase mydatabase
在MongoDB shell中執行以下命令查看用戶權限:
db.runCommand({ connectionStatus: 1 })
通過以上步驟,你就可以在CentOS上成功配置MongoDB認證。