您的位置:首页 > 数据库 > Mongodb

MongoDB用户权限管理

2018-02-09 17:10 531 查看
授权用户readwrite有test1库的读写权限:

> use test1
switched to db test1

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

验证授权是否正确:

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

注意:用户授权的时候一定要遵守规范,不然可能会出现连不上的情况,来举个例子

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,先切换到要授权的库下面再来创建用户
建议采用第二种方法,无论如何最好就是固定采用一种方式,这样可以节省与开发的沟通成本

mongodb角色表



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb 用户授权