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 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论