Máxima Alekz
Máxima Alekz

Reputation: 582

MongoDB - Collection-level roles

I have a trouble. I'm trying to apply a role to user. I want the user only find, insert, remove and update specific collection

I'm doing this.

  1. Create role:

    db.createRole({role:'user_role_col',privileges:[{resource:{db:'something_else', collection: 'col_something_else'}, actions: ['find','remove','insert','update']}], roles: []}); .

  2. Create user with that role:

    db.createUser({user: 'user_col',pwd: '1234',roles: [{role: "user_role_col", db: "something_else"}]}) .

When I created role and user, I stay on something_else database (use something_else)

0 errors got, but I can only read col_something_else, I cannot remove, update, or insert :(

What am I doing wrong?

Upvotes: 1

Views: 1484

Answers (1)

kevinadi
kevinadi

Reputation: 13775

I believe the following commands replicates what you did. Here I'm creating the role and user in the test database:

> use test

> db.createRole({role: 'testRole', privileges: [{resource: {db:'test', collection:'test'}, actions:['find','update','insert','remove']}], roles: []})

> db.createUser({user:'testUser',pwd:'password',roles:[{role:'testRole', db:'test'}]})

I would then have to quit the mongo shell and re-authenticate using the new credentials. However, the authenticationDatabase parameter must point to the test database, since that's where I created the role and the user:

$ mongo -u testUser -p password --authenticationDatabase test

> db.test2.insert({a:1})  //try inserting to a non-"test" collection
unauthorized

> db.test2.find()  //try find on a non-"test" collection
unauthorized

> db.test.insert({a:1})  //insert into "test" collection
Inserted 1 record(s)

> db.test.updateMany({},{$set:{a:2}})  //update "test" collection
{
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1
}

> db.test.find()  //find on "test" collection
{
  "_id": ObjectId("5a0bcfa4322032cfcc3a69c6"),
  "a": 2
}

> db.test.deleteOne({a:2})  //delete from "test" collection
{
  "acknowledged": true,
  "deletedCount": 1
}

> db.test.drop()  //try to drop "test" collection
2017-11-15T16:32:07.715+1100 E QUERY    [thread1] Error: drop failed: {
  "ok": 0,
  "errmsg": "not authorized on test to execute command { drop: \"test\" }",
  "code": 13,
  "codeName": "Unauthorized"
}

I found that the new custom role (testRole) is authorized correctly. This is using MongoDB 3.4.10.

Upvotes: 3

Related Questions