在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中配置了认证。