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

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> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值