標籤:
定義:
建立一個資料庫新使用者用db.createUser()方法,如果使用者存在則返回一個使用者重複錯誤。
文法:
db.createUser(user, writeConcern)
user這個文檔建立關於使用者的身份認證和訪問資訊;
writeConcern這個文檔描述保證MongoDB提供寫操作的成功報告。
· user文檔,定義了使用者的以下形式:
{ user: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
]
}
user文檔欄位介紹:
user欄位,為新使用者的名字;
pwd欄位,使用者的密碼;
cusomData欄位,為任意內容,例如可以為使用者全名介紹;
roles欄位,指定使用者的角色,可以用一個空數組給新使用者設定空角色;
在roles欄位,可以指定內建角色和使用者定義的角色。
Built-In Roles(內建角色):
1. 資料庫使用者角色:read、readWrite;
2. 資料庫管理角色:dbAdmin、dbOwner、userAdmin;
3. 叢集管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4. 備份恢複角色:backup、restore;
5. 所有資料庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6. 超級使用者角色:root
// 這裡還有幾個角色間接或直接提供了系統超級使用者的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
7. 內部角色:__system
PS:關於每個角色所擁有的操作許可權可以點擊上面的內建角色連結查看詳情。
· writeConcern文檔(官方說明)
w選項:允許的值分別是 1、0、大於1的值、"majority"、<tag set>;
j選項:確保mongod執行個體寫資料到磁碟上的journal(日誌),這可以確保mongd以外關閉不會遺失資料。設定true啟用。
wtimeout:指定一個時間限制,以毫秒為單位。wtimeout只適用於w值大於1。
例如:在products資料庫建立使用者accountAdmin01,並給該使用者admin資料庫上clusterAdmin和readAnyDatabase的角色,products資料庫上readWrite角色。
use products
db.createUser( { "user" : "accountAdmin01",
"pwd": "cleartext password",
"customData" : { employeeId: 12345 },
"roles" : [ { role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
] },
{ w: "majority" , wtimeout: 5000 } )
驗證:
mongo -u accountAdmin01 -p yourpassward --authenticationDatabase products
MongoDB 3.0以上版本設定存取權限、設定使用者