I have to restrict few MongoDB users to specific collections with some specific action permissions(only Update collection). As per the docs it's possible.
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
Logging in as the 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
If I should tell briefly what I did above,
- Created 'foo' database with a collection 'inventory'
- Created a role 'fooRole' with 'find' & 'update' -
db.createRole({ role: "fooRole", privileges: [ { resource: { db: "foo", collection: "inventory" }, actions: [ "find", "update" ] } ], roles: [] })
- Created user 'foouser' with role 'fooRole' -
db.createUser({ user: "foouser", pwd: "foopass", roles: [ { role: "fooRole", db: "foo" } ] })
Why it doesn't work?. Why foouser
can drop collection and database?
Am I doing anything wrong?. Please suggest some solution!.