How do you change MongoDB user permissions?

2019-03-22 22:23发布

For instance, if I have this user:

> db.system.users.find()
{ "user" : "testAdmin", "pwd" : "[some hash]", "roles" : [ "clusterAdmin" ], "otherDBRoles" : { "TestDB" : [ "readWrite" ]  } }

And I want to give that user the dbAdmin permissions on the TestDB database, I can remove the user record then add it back with the new permissions:

> db.system.users.remove({"user":"testAdmin"})
> db.addUser( { user: "testAdmin",
                  pwd: "[whatever]",
                  roles: [ "clusterAdmin" ],
                  otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] } } )

But that seems hacky and error-prone.

And I can update the table record itself:

> db.system.users.update({"user":"testAdmin"}, {$set:{ otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] }}})

But I'm not sure if that really creates the correct permissions - it looks fine but it may be subtly wrong.

Is there a better way to do this?

标签: mongodb rbac
2条回答
贼婆χ
2楼-- · 2019-03-22 22:42

See array update operators.

> db.users.findOne()
{
    "_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
    "user" : "testAdmin",
    "pwd" : "[some hash]",
    "roles" : [
        "clusterAdmin"
    ],
    "otherDBRoles" : {
        "TestDB" : [
            "readWrite"
        ]
    }
}
> db.users.update({"user" : "testAdmin"}, {$addToSet: {'otherDBRoles.TestDB': 'dbAdmin'}}, false, false)
> db.users.findOne()
{
    "_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
    "user" : "testAdmin"
    "pwd" : "[some hash]",
    "roles" : [
        "clusterAdmin"
    ],
    "otherDBRoles" : {
        "TestDB" : [
            "readWrite",
            "dbAdmin"
        ]
    },
}

Update:

MongoDB checks permission on every access. If you see operator db.changeUserPassword:

> db.changeUserPassword
function (username, password) {
    var hashedPassword = _hashPassword(username, password);
    db.system.users.update({user : username, userSource : null}, {$set : {pwd : hashedPassword}});
    var err = db.getLastError();
    if (err) {
        throw "Changing password failed: " + err;
    }
}

You will see — operator changes user's document.

See also system.users Privilege Documents and Delegated Credentials for MongoDB Authentication

查看更多
疯言疯语
3楼-- · 2019-03-22 22:46

If you want to just update Role of User. You can do in the following way

db.updateUser( "userName",
               {

                 roles : [
                           { role : "dbAdmin", db : "dbName"  },
                           { role : "readWrite", db : "dbName"  }
                         ]
                }
             )

Note:- This will override only roles for that user.

查看更多
登录 后发表回答