MongoDb用户创建以及权限控制
19-05-27 18:06
字数 1439
阅读 2654
已编辑
我们在安装完mongodb之后,默认是没有开启权限认证的, 但是我们在生产环境权限认证是必不可少的
1. 创建用户
启动mongo shell
我们先创建个管理员账号(该账号可以对所有数据库进行用户管理)
> mongo
> use admin
switched to db admin
> db.createUser(
... {
... user: "admin",
... pwd: "123456",
... roles: [ { role: "userAdminAnyDatabase", db: "admin"} ]
... }
... )
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
>
2. 开启权限认证
编辑mongodb.conf
,添加 auth = true
重启mongodb
mongo -port 27017 -u "admin" -p "123456" --authenticationDatabase "admin"
> use admin
switched to db admin
> show users;
{
"_id" : "admin.admin",
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
>
连接好了之后,再认证
>mongo
MongoDB shell version v4.0.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.1
> use admin
switched to db admin
> db.auth("admin", "123456")
1
> show users;
{
"_id" : "admin.admin",
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
>
根据具体的库创建具体的账号
比如有个库是test
,创建一个有读写权限的账号
mongo -port 27017 -u "admin" -p "123456" --authenticationDatabase "admin"
> use test;
switched to db test
> db.createUser(
... {
... user : "my_tester",
... pwd : "123456",
... roles: [ { role : "readWrite", db : "test" } ]
... }
... )
Successfully added user: {
"user" : "my_tester",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
> show users;
{
"_id" : "test.my_tester",
"user" : "my_tester",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.auth("test", "123456")
1
2人点赞>
0 条评论
排序方式
时间
投票
快来抢占一楼吧
请登录后发表评论
文章归档
2024-08
1 篇
2024-03
1 篇
2023-11
1 篇
2023-08
1 篇
2023-07
1 篇
展开剩余 26 条
2022-08
1 篇
2021-10
0 篇
2021-07
1 篇
2021-01
1 篇
2020-09
2 篇
2020-07
2 篇
2020-05
1 篇
2020-01
2 篇
2019-10
1 篇
2019-06
1 篇
2019-05
1 篇
2019-03
1 篇
2018-12
2 篇
2018-11
1 篇
2018-07
1 篇
2018-06
2 篇
2018-05
1 篇
2017-12
3 篇
2017-11
4 篇
2017-10
4 篇
2017-09
1 篇
2017-06
1 篇
2017-05
1 篇
2017-03
3 篇
2017-02
6 篇
2017-01
2 篇
最新文章
最受欢迎
08-01 17:09
03-13 21:56
23-11-08 20:31
23-08-12 14:12