1、mongodb添加用户认证

  mongodb默认是不添加用户认证的,但是出于对数据安全的考虑还是需要添加用户认证。先来展示一下有用户和无用户的情况:

mongo 10.10.16.228:27017  #无用户可直接登录,默认可以不用添加ip和端口号
mongo -uadmin -p'aqMkDuYbRAvfgJk' 10.10.16.228:27017/admin #有用户需要加上用户名和密码

  下面开始创建admin这个库的管理者并设置密码:(该账号需要有grant权限,即:账号管理的授权权限。注意一点,帐号是跟着库走的,所以在指定库里授权,必须也在指定库里验证(auth)。

mongo 127.0.0.1:27017
MongoDB shell version v4.0.4
connecting to: mongodb://127.0.0.1:27017/test
Implicit session: session { "id" : UUID("b267a3ff-196a-4bb7-9d1f-167940f3b764") }
MongoDB server version: 4.0.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
2018-12-25T09:21:22.807+0800 I CONTROL  [initandlisten] 
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use admin  
switched to db admin
> db.createUser( { user:'Admin', pwd:'aqMkDuYbRAvfgJk', roles:["root"] } );   #为admin这个库创建Admin用户,密码是aqMkDuYbRAvfgJk 权限(roles)是root
Successfully added user: { "user" : "Admin", "roles" : [ "root" ] }
> use wyy
switched to db wyy  #创建wyy库
> db.createUser( { user:'wyy', pwd:'wyy123', roles:["readWrite"] } );
Successfully added user: { "user" : "wyy", "roles" : [ "readWrite" ] }  #单独为这个库授权认证用户
> 
> show users
{
    "_id" : "wyy.wyy",
    "user" : "wyy",
    "db" : "wyy",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "wyy"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}
> use admin
switched to db admin 
> show collections
system.indexes
system.users
system.version
> show users
{
    "_id" : "admin.Admin",
    "user" : "dbAdmin",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
# 至此mongo添加用户认证完成
View Code

相关文章: