標籤:roles cat png 服務 col ase 串連 讀寫 omd
授權使用者readwrite有test1庫的讀寫權限:
> use test1switched to db test1> db.createUser({user: "readwrite",pwd: "readwrite",customData: {description: "測試使用者readwrite"},roles: [{role: "readWrite",db: "test1"}]})
驗證授權是否正確:
mongo -ureadwrite -preadwrite --authenticationDatabase test1MongoDB shell version: 3.2.16connecting to: test
注意:使用者授權的時候一定要遵守規範,不然可能會出現連不上的情況,來舉個例子
mongo -uroot -proot --authenticationDatabase adminMongoDB shell version: 3.2.16connecting to: test> db.createUser({... user: "readwrite1",... pwd: "readwrite1",... customData: {... description: "測試使用者1"... },... roles: [{... role: "readWrite",... db: "test1"... }]... })
我們上面建立了readwrite1使用者,這個使用者與前面的readwrite使用者不同之處在於它在是test庫下面授權的,
mongo -ureadwrite1 -preadwrite1 --authenticationDatabase test1MongoDB shell version: 3.2.16connecting to: test2018-02-08T23:17:20.762+0800 E QUERY [thread1] Error: Authentication failed. :[email protected]/mongo/shell/db.js:1441:20@(auth):6:1@(auth):1:2exception: login failed mongo -ureadwrite1 -preadwrite1 --authenticationDatabase testMongoDB shell version: 3.2.16connecting to: test>
可以看到如果--authenticationDatabase沒有指定成授權的庫就會連不上mongo服務,為了避免出現類似這種情況,有兩種解決方案:
1,建立使用者的時候在test庫下面建立,因為預設串連的就是test庫
2,先切換到要授權的庫下面再來建立使用者
建議採用第二種方法,無論如何最好就是固定採用一種方式,這樣可以節省與開發的溝通成本
mongodb角色表
MongoDB使用者權限管理