1.用户权限说明
image.png2.用户创建语法
{
user: "<name>",user字段:用户的名字;
pwd: "<cleartext password>",pwd字段:用户的密码;
customData: { <any information> },cusomData字段:为任意内容
roles: [
roles字段:指定用户的角色,可以用一个空数组给新用户设定空角色;
{ role: "<role>",
db: "<database>" } | "<role>",
...
]
}
roles 字段:可以指定内置角色和用户定义的角色。
roles字段:指定用户的角色,可以用一个空数组给新用户设定空角色;
3.创建管理员用户
3.1进入管理数据库
> use admin
创建管理用户,root权限
>db.createUser(
{
user: "root",
pwd: "root",
roles: [ { role: "root", db: "admin" } ]
}
)
注意:
创建管理员角色用户的时候,必须到admin下创建。删除的时候也要到相应的库下操作。
3.2查看创建完用户后的collections;
>use admin
> show collections;
system.users # 用户存放位置
system.version
> db.system.users.find().pretty()
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "v3v1oEvwvX70i+ENCkSiLQ==",
"storedKey" : "aswu2GvDubCXFokl72ZVYzgW1DA=",
"serverKey" : "6maLC10hXo+MJACBWhkwEfRuRkE="
}
},
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
> show users (只能查询本库)
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
3.3.验证用户是否能用
> db.auth("root","root")
1 # 返回 1 即为成功
3.4.用户创建完成后在配置文件中开启用户验证
cat >>/etc/mongod.conf<<-'EOF'
security:
authorization: enabled
EOF
** *之后需要重启服务****
4登录MongoDB
方法一:命令行中进行登陆
[mongod@MongoDB ~]$ mongo -uroot -proot admin
MongoDB shell version: 3.2.8
connecting to: admin
方法二:在数据库中进行登陆验证:
[mongod@MongoDB ~]$ mongo
MongoDB shell version: 3.2.8
connecting to: test
> use admin
switched to db admin
> db.auth("root","root")
1
> show tables;
system.users
system.version
5按生产需求创建应用用户
创建只读用户
5.11在test库创建只读用户test
use test
db.createUser(
{
user: "test",
pwd: "test",
roles: [ { role: "read", db: "test" } ]
}
)
5.1.2测试用户是否创建成功
db.auth("test","test")
show users;
5.1.3登录test用户,并测试是否只读
show collections;
db.createCollection('b')
5.2创建某库的读写用户
5.2.1创建test1用户,权限为读写
db.createUser(
{
user: "test1",
pwd: "test1",
roles: [ { role: "readWrite", db: "test" } ]
}
)
5.2.2查看并测试用户
show users;
db.auth("test1","test1")
5.3创建对多库不同权限的用户
5.3.1创建对app为读写权限,对test库为只读权限的用户
use app
db.createUser(
{
user: "app",
pwd: "app",
roles: [ { role: "readWrite", db: "app" },
{ role: "read", db: "test" }
]
}
)
5.3.2查看并测试用户
show users
db.auth("app","app")
6.删除用户
1.删除app用户:先登录到admin数据库
mongo -uroot –proot 127.0.0.1/admin
2.进入app库删除app用户
use app
db.dropUser("app")
7. 自定义数据库
1.创建app数据库的管理员:先登录到admin数据库
use app
db.createUser(
{
user: "admin",
pwd: "admin",
roles: [ { role: "dbAdmin", db: "app" } ]
}
)
2.创建app数据库读写权限的用户并具有clusterAdmin权限:
use app
db.createUser(
{
user: "app04",
pwd: "app04",
roles: [ { role: "readWrite", db: "app" },
{ role: "clusterAdmin", db: "admin" }
]
}
)
网友评论