MongoDB创建只读用户并授权指定集合的查询权限

创建测试数据

use testdb
db.test_t.insertOne({id:1,name:'zhangsan'});
db.test_t.insertOne({id:2,name:'lisi'});
db.test_t1.insertOne({id:1,name:'zhangsan'});
db.test_t1.insertOne({id:2,name:'lisi'});
db.test_t2.insertOne({id:1,name:'zhangsan'});

创建一个自定义角色,只允许在 testdb 数据库的 test_t1test_t2 集合上执行查询操作。

use testdb

db.createRole({
  role: "read_testdb",  // 角色名称
  privileges: [
    {
      resource: { db: "testdb", collection: "test_t1" },  // 对testdb数据库下的test_t1集合授予权限
      actions: [ "find" ]  // 允许查询操作(find)
    },
    {
      resource: { db: "testdb", collection: "test_t2" },  // 对testdb数据库下的test_t2集合授予权限
      actions: [ "find" ]
    }
  ],
  roles: []  // 没有继承其他角色
})

创建用户并分配角色

use testdb

db.createUser({
  user: "test_user",  // 用户名
  pwd: "test_user",  // 用户密码
  roles: [
    { role: "read_testdb", db: "testdb" }  // 分配刚才创建的角色
  ]
})

验证权限

[mongodb@mongo190 ~]$ mongosh -u test_user -p test_user 192.168.1.190:27017/testdb
Current Mongosh Log ID: 6736122884c4113b2f1bd68d
Connecting to:          mongodb://<credentials>@192.168.1.190:27017/testdb?directConnection=true&appName=mongosh+1.10.1
Using MongoDB:          6.0.6
Using Mongosh:          1.10.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

 
Enterprise testdb> db.test_t1.find()
[
  {
    _id: ObjectId("67360308cd77db51ff44f83a"),
    id: 1,
    name: 'zhangsan'
  },
  { _id: ObjectId("67360308cd77db51ff44f83b"), id: 2, name: 'lisi' }
]
Enterprise testdb> db.test_t2.find()
[
  {
    _id: ObjectId("67360371cd77db51ff44f83c"),
    id: 1,
    name: 'zhangsan'
  }
]
Enterprise testdb> db.test_t.find()
MongoServerError: not authorized on testdb to execute command { find: "test_t", filter: {}, lsid: { id: UUID("89d7523d-ce34-41f7-bb6e-d304e3ccf66a") }, $db: "testdb" }
Enterprise testdb> 
11-20 09:45