mongodb创建了视图后会生成system.views,但是没有权限查询

发布时间 2023-07-26 17:31:00作者: slnngk

环境:
OS:Centos 7
mongodb:5.0.19


mongodb创建了视图后会生成system.views,但是没有权限查询

myrepl:PRIMARY> db.system.views.find()
Error: error: {
        "ok" : 0,
        "errmsg" : "not authorized on db_pushmsg to execute command { find: \"system.views\", filter: {}, lsid: { id: UUID(\"b8dad2cf-e9d1-43ab-8677-78a9ce0d3438\") }, $db: \"db_pushmsg\" }",
        "code" : 13,
        "codeName" : "Unauthorized"
}

 

解决办法(在admin用户下操作,test为超级账号):
use admin
db.runCommand({createRole: "readViewCollection01", privileges: [{resource: { db: "", collection: "system.views" }, actions: [ "find"] }],roles : []})
db.grantRolesToUser('test',['readViewCollection01']);
这样使用admin登录就可以查看了
use admin
db.auth("test","test123");

 

若使用普通用户能够访问

use admin
db.auth("test","test123");
use db_pushmsg
db.runCommand({createRole: "readViewCollection01", privileges: [{resource: { db: "", collection: "system.views" }, actions: [ "find"] }],roles : []})


myrepl:PRIMARY> db.runCommand({createRole: "readViewCollection01", privileges: [{resource: { db: "", collection: "system.views" }, actions: [ "find"] }],roles : []})
{
        "ok" : 0,
        "errmsg" : "Roles on the 'db_pushmsg' database cannot be granted privileges that target other databases or the cluster",
        "code" : 49,
        "codeName" : "InvalidRoleModification"
}

 

需要具体指定库

db.runCommand({createRole: "readViewCollection01", privileges: [{resource: { db: "db_pushmsg", collection: "system.views" }, actions: [ "find"] }],roles : []})
db.grantRolesToUser('hxl',['readViewCollection01']);
myrepl:PRIMARY> show users
{
        "_id" : "db_pushmsg.hxl",
        "userId" : UUID("f45ace6a-efde-478f-ad7b-57c490d35a0c"),
        "user" : "hxl",
        "db" : "db_pushmsg",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "db_pushmsg"
                },
                {
                        "role" : "readViewCollection01",
                        "db" : "db_pushmsg"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

 

这样就可以使用普通用户hxl验证访问system.views表了
[root@localhost key]# /usr/local/services/mongodb/bin/mongo 192.168.1.105:29001
use db_pushmsg
db.auth("hxl","hxl123");

myrepl:PRIMARY> db.system.views.find()
{ "_id" : "db_pushmsg.orderInfo", "viewOn" : "order", "pipeline" : [ { "$match" : { "orderTime" : { "$gte" : ISODate("2022-01-26T00:00:00Z") } } }, { "$sort" : { "price" : -1 } }, { "$limit" : 10 }, { "$project" : { "_id" : 0, "orderNo" : 1, "price" : 1, "orderTime" : 1 } } ] }