MongoDB用户权限管理

受权用户readwrite有test1库的读写权限:mongodb

> use test1
switched to db test1

> db.createUser({
user: "readwrite",
pwd: "readwrite",
customData: {
description: "测试用户readwrite"
},
roles: [{
role: "readWrite",
db: "test1"
}]
})

验证受权是否正确:shell

mongo -ureadwrite -preadwrite --authenticationDatabase test1
MongoDB shell version: 3.2.16
connecting to: test

注意:用户受权的时候必定要遵照规范,否则可能会出现连不上的状况,来举个例子ide

mongo -uroot -proot --authenticationDatabase admin
MongoDB shell version: 3.2.16
connecting to: test
>  db.createUser({
... user: "readwrite1",
... pwd: "readwrite1",
... customData: {
... description: "测试用户1"
... },
... roles: [{
... role: "readWrite",
... db: "test1"
... }]
... })

咱们上面建立了readwrite1用户,这个用户与前面的readwrite用户不一样之处在于它在是test库下面受权的,测试

mongo -ureadwrite1 -preadwrite1 --authenticationDatabase test1
MongoDB shell version: 3.2.16
connecting to: test
2018-02-08T23:17:20.762+0800 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2

exception: login failed

 mongo -ureadwrite1 -preadwrite1 --authenticationDatabase test
MongoDB shell version: 3.2.16
connecting to: test
>

能够看到若是--authenticationDatabase没有指定成受权的库就会连不上mongo服务,为了不出现相似这种状况,有两种解决方法:
1,建立用户的时候在test库下面建立,由于默认链接的就是test库
2,先切换到要受权的库下面再来建立用户
建议采用第二种方法,不管如何最好就是固定采用一种方式,这样能够节省与开发的沟通成本prototype

mongodb角色表
MongoDB用户权限管理
MongoDB用户权限管理code

相关文章
相关标签/搜索