MongoDB设置用户名以及密码

MongoDB 默认没有设置用户名密码,需要我们自己设置。简单来说首先设置一个管理所有用户角色的用户admin,然后根据需要为此用户添加其他角色即可。

1.设置一个管理所有用户角色的用户admin

例如,以下内容使用角色和 角色myUserAdminadmin数据库中 创建用户

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

注意上面代码中的passwordPrompt():

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.

mongoshell的4.2版开始,您可以将该passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用来提示输入密码,而不是直接在方法/命令调用中指定密码。但是,您仍然可以像使用早期版本的mongoshell 一样直接指定密码 。

然后需要授权(笔者在执行上面操作之后没有重启直接进行下一步可以实现):

use admin  //如果不重启可以,可以不用输入这句
db.auth("myUserAdmin", "abc123" )

返回1表示成功。

2.创建数据库用户

use test
db.createUser(
  {
    user: "myTester",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

猜你喜欢

转载自www.cnblogs.com/w-honey/p/11402900.html