创建用户
语法:
db.createUser(
{
user:<name_string>, #字符串
pwd:<password_strin>, #字符串
roles:[{role:<role_name>,db:<db_name>}] #数组
}
)
创建用户:
> db.createUser(
... {
... user:"root",
... pwd:"admin",
... roles:[{role:"root",db:"admin"}]
... }
... )
用户验证:
> db.auth("root","admin")
1
查看用户:
删除用户
db.dropUser(<user_name>) #删除某个用户,授受字符串参数
db.dropAllUsers() #删除当前库的所有用户
查询所有用户
> db.getUsers()
[
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
},
{
"_id" : "admin.sysadmin",
"user" : "sysadmin",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
},
{
"_id" : "admin.test",
"user" : "test",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
]
删除test用户
> db.dropUser("test")
true
确认test用户是否存在
> db.getUser("test")
null
删除所有用户
> db.dropAllUsers()
2
修改用户密码
要修改用户密码,要求用户具有changePassword或changeOwnPassword的权限,有以下两种方式用来修改用户密码:
db.changeUserPassword(<user_name>,<new_password>)
db.updateUser(<user_name>,{update_object})
db.changeUserPassword()示例:
admin@undefined$ db.auth("root","admin")
1
admin@undefined$ db.changeUserPassword("root","123456")
admin@undefined$ db.auth("root","admin")
Error: Authentication failed.
0
admin@undefined$ db.auth("root","123456")
1
admin@undefined$ show dbs
admin 0.000GB
local 0.000GB
test 0.000GB
test1 0.000GB
可以看到在修改root用户的密码后,原来的密码验证就失败了,但是当前这个会话还是可以正常执行操作,新会话则需要用修改后的密码进行验证
db.updateUser()示例:
admin@undefined$ db.auth("root","123456")
1
admin@undefined$ db.updateUser("root",{pwd:"admin123"})
admin@undefined$ db.auth("root","admin123")
1
admin@undefined$ db.auth("root","123456")
Error: Authentication failed.
0
修改用户权限(角色):
修改用户角色也是使用db.updateUser()函数来实现的
我们先创建一个测试用户readtest,它只对test库具备读权限:
db.createUser(
{
user:"readtest",
pwd:"123456",
roles:[{role:"read",db:"test"}]
}
)
admin@undefined$ db.auth("readtest","123456")
1
admin@undefined$ use test
switched to db test
test@undefined$ show tables
goods
users
test@undefined$ db.goods.find()
{ "_id" : ObjectId("5a7c5b7e83dba596ccad3ac0"), "sn" : "fhbowhnlerio12o47", "category" : "food" }
test@undefined$ db.goods.insert({"sn":"04t68gjsoe076","category" : "beauty"})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on test to execute command { insert: \"goods\", documents: [ { _id: ObjectId('5a8ef5aa3cdd503ad3903fcc'), sn: \"04t68gjsoe076\", category: \"beauty\" } ], ordered: true }"
}
})
可以看到这个用户可以执行读操作,写操作是没有权限的,现在我们通过db.updateUser()来扩充它的权限,记其具有读写权限。admin@undefined$ db.updateUser("readtest",{"roles":[{role:"readWrite",db:"test"}]})
admin@undefined$ db.auth("readtest","123456")
1
admin@undefined$ use test
switched to db test
test@undefined$ db.goods.insert({"sn":"04t68gjsoe076","category" : "beauty"})
WriteResult({ "nInserted" : 1 })
可以看到,当我们把readtest用户的角色从read改成readWrite时,它就具有了对test库的写权限。通过db.updateUser()我们可以实现用户权限的放大和缩小
来源:51CTO
作者:emma_cql
链接:https://blog.51cto.com/chenql/2072153