MongoDB 默认没有设置用户名密码,需要我们自己设置,先设置 admin 用户,然后针对某个数据库设置用户。
设置 admin
# 进入控制台
mongo
创建管理员
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
重启 MongoDB
重启并进入控制台
mongod --auth
mongo
授权
use admin
db.auth("myUserAdmin", "abc123" )
添加数据库用户
没添加用户之前,操作数据库会报错:
> use test
switched to db test
> db.foo.insert( { x: 1, y: 1 } )
WriteCommandError({
"ok" : 0,
"errmsg" : "too many users are authenticated",
"code" : 13,
"codeName" : "Unauthorized"
})
添加用户:
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
重新进入控制台,授权、执行插入操作:
> use test
switched to db test
> db.auth("myTester", "xyz123" )
1
> db.foo.insert( { x: 1, y: 1 } )
WriteResult({ "nInserted" : 1 })