MongoDB用戶權限管理

受權用戶readwrite有test1庫的讀寫權限:mongodb

> use test1
switched to db test1

> db.createUser({
user: "readwrite",
pwd: "readwrite",
customData: {
description: "測試用戶readwrite"
},
roles: [{
role: "readWrite",
db: "test1"
}]
})

驗證受權是否正確:shell

mongo -ureadwrite -preadwrite --authenticationDatabase test1
MongoDB shell version: 3.2.16
connecting to: test

注意:用戶受權的時候必定要遵照規範,否則可能會出現連不上的狀況,來舉個例子ide

mongo -uroot -proot --authenticationDatabase admin
MongoDB shell version: 3.2.16
connecting to: test
>  db.createUser({
... user: "readwrite1",
... pwd: "readwrite1",
... customData: {
... description: "測試用戶1"
... },
... roles: [{
... role: "readWrite",
... db: "test1"
... }]
... })

咱們上面建立了readwrite1用戶,這個用戶與前面的readwrite用戶不一樣之處在於它在是test庫下面受權的,測試

mongo -ureadwrite1 -preadwrite1 --authenticationDatabase test1
MongoDB shell version: 3.2.16
connecting to: test
2018-02-08T23:17:20.762+0800 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2

exception: login failed

 mongo -ureadwrite1 -preadwrite1 --authenticationDatabase test
MongoDB shell version: 3.2.16
connecting to: test
>

能夠看到若是--authenticationDatabase沒有指定成受權的庫就會連不上mongo服務,爲了不出現相似這種狀況,有兩種解決方法:
1,建立用戶的時候在test庫下面建立,由於默認鏈接的就是test庫
2,先切換到要受權的庫下面再來建立用戶
建議採用第二種方法,不管如何最好就是固定採用一種方式,這樣能夠節省與開發的溝通成本prototype

mongodb角色表
MongoDB用戶權限管理
MongoDB用戶權限管理code

相關文章
相關標籤/搜索