mongodb版本爲3.2.10(目前最新),演示的是linux下的mongodb受權認證linux
service mongod start
默認的啓動mongod是不開啓受權登陸的。個人MongoDB是使用的yum安裝的。詳見《在CentOS 6.x 64bit上安裝MongoDB 3.2社區版》。因此,mongod是安裝在:/usr/bin/mongod,配置文件的路徑:/etc/mongod.conf。mongodb
show dbs;
看到只有一個local數據庫,admin是不存在的(這是3.0以上版本改變了的),咱們須要本身給他建立個admin數據庫。shell
use admin db.createUser({ user: "mongoadmin" , pwd: "mongoadmin", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]});
vi /etc/mongo.conf
在配置文件中增長數據庫
security: authorization: "enabled"
當你運行 show dbs;的時候會出現下面的提示:spa
~ mongo MongoDB shell version: 3.2.10 connecting to: 127.0.0.1/test > show dbs; 2016-11-15T09:26:16.883+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }", "code" : 13 } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1 shellHelper.show@src/mongo/shell/utils.js:761:19 shellHelper@src/mongo/shell/utils.js:651:15 @(shellhelp2):1:1
這說明已經啓用受權管理了。.net
運行prototype
db.auth('mongoadmin','mongoadmin');
就能夠執行相關的操做命令了。code
使用mongoadmin受權操做視乎權限有點兒大。我們能夠爲每一個db受權一個用戶來進行操做。blog
use myTest db.createUser( { user: "test", pwd: "123456", roles: [ { role: "readWrite", db: "myTest" } ] } )
這樣就能夠爲myTest添加了test的受權用戶,test用戶能夠對myTest進行讀寫操做,因爲它不是一個操做用戶。因此,不能對admin數據庫進行操做。get