授权用户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角色表
本文转自 emma_cql 51CTO博客,原文链接:http://blog.51cto.com/chenql/2070723