如何更改 MongoDB 用户权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16527033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you change MongoDB user permissions?
提问by Ed Norris
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:
我想授予该用户dbAdmin
对TestDB
数据库的权限,我可以删除用户记录,然后使用新权限将其添加回来:
> 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?
有一个更好的方法吗?
回答by Vaibhav
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.
注意:- 这将仅覆盖该用户的角色。
回答by Vladimir Korshunov
请参阅数组更新运算符。
> 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
:
MongoDB 检查每次访问的权限。如果您看到操作员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.
您将看到 —?operator 更改用户的文档。
See also system.users
Privilege Documentsand Delegated Credentials for MongoDB Authentication