How do you change MongoDB user permissions?

前端 未结 2 1429
我在风中等你
我在风中等你 2021-02-12 04:09

For instance, if I have this user:

> db.system.users.find()
{ \"user\" : \"testAdmin\", \"pwd\" : \"[some hash]\", \"roles\" : [ \"clusterAdmin\" ], \"otherDB         


        
相关标签:
2条回答
  • 2021-02-12 04:15

    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

    0 讨论(0)
  • 2021-02-12 04:26

    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.

    0 讨论(0)
提交回复
热议问题