我必须限制少数 MongoDB 用户只能使用特定操作权限(仅限更新集合)。根据文档这是可能的。
localhost:tmp username$ mongo
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.1
Server has startup warnings:
2018-05-06T15:30:51.739+0530 I CONTROL [initandlisten]
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten]
>
>
>
> use foo
switched to db foo
> db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )
{
"acknowledged" : true,
"insertedId" : ObjectId("5af6c7e058d94deb0777e883")
}
>
>
>
> db.inventory.find( { item: "canvas" } )
{ "_id" : ObjectId("5af6c7e058d94deb0777e883"), "item" : "canvas", "qty" : 100, "tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }
>
>
>
> show collections
inventory
> db.createRole({ role: "fooRole", privileges: [ { resource: { db: "foo", collection: "inventory" }, actions: [ "find", "update" ] } ], roles: [] })
{
"role" : "fooRole",
"privileges" : [
{
"resource" : {
"db" : "foo",
"collection" : "inventory"
},
"actions" : [
"find",
"update"
]
}
],
"roles" : [ ]
}
>
>
>
>
> db.createUser({ user: "foouser", pwd: "foopass", roles: [ { role: "fooRole", db: "foo" } ] })
Successfully added user: {
"user" : "foouser",
"roles" : [
{
"role" : "fooRole",
"db" : "foo"
}
]
}
>
>
>
bye
以 foouser 身份登录,
localhost:tmp username$ mongo -u "foouser" -p "foopass" --authenticationDatabase "foo"
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.1
Server has startup warnings:
2018-05-06T15:30:51.739+0530 I CONTROL [initandlisten]
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2018-05-06T15:30:51.772+0530 I CONTROL [initandlisten]
>
>
> use foo
switched to db foo
> show collections
inventory
> db.inventory.drop()
true
> show collections
> db.dropDatabase()
{ "dropped" : "foo", "ok" : 1 }
>
bye
如果我应该简要地讲述一下我上面所做的事情,
- 创建了“foo”数据库,其中包含“inventory”集合
- 使用“find”和“update”创建了一个角色“fooRole”-
db.createRole({ role: "fooRole", privileges: [ { resource: { db: "foo", collection: "inventory" }, actions: [ "find", "update" ] } ], roles: [] })
- 创建具有角色“fooRole”的用户“foouser”-
db.createUser({ user: "foouser", pwd: "foopass", roles: [ { role: "fooRole", db: "foo" } ] })
为什么它不起作用?为什么foouser
可以删除集合和数据库?我做错了什么吗?请提出一些解决方案!
答案1
虽然您已经创建了用户,但记录中的启动警告表明您尚未启用访问控制:
** WARNING: Access control is not enabled for the database.
** Read and write access to data and configuration is unrestricted.
与 MongoDB 3.6 一样,必须使用security.authorization
配置设置或--auth
命令行选项。
有关完整步骤,请参阅启用 Auth 教程在 MongoDB 手册中。