在MongoDB中,配置認證可以通過以下步驟實現:
admin
數據庫:mongo -u root -p your_root_password --authenticationDatabase admin
接下來,創建一個管理員用戶并設置密碼:
use admin
db.createUser({
user: "admin",
pwd: "your_admin_password",
roles: ["root"]
})
mongod.conf
(Linux/macOS)或mongod.cfg
(Windows)配置文件中添加以下內容:security:
authorization: enabled
這將啟用MongoDB的內部認證系統。
sudo systemctl restart mongod
sudo service mongod restart
brew services restart mongodb-community
mongo -u admin -p your_admin_password --authenticationDatabase admin
myDatabase
的數據庫創建一個具有讀取和寫入權限的用戶,請執行以下命令:use myDatabase
db.createUser({
user: "myUser",
pwd: "your_user_password",
roles: ["readWrite"]
})
現在,你可以使用新創建的用戶登錄到MongoDB:
mongo -u myUser -p your_user_password --authenticationDatabase myDatabase
這樣,你就成功地在MongoDB中配置了認證。