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" } ]
  }
)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM