在 mongo.conf文件中加入 auth=true,開啟權(quán)限功能
編輯文件
> sudo gedit /etc/mongo.conf
創(chuàng)建用戶
進(jìn)入mongodb
> mongo
必須先切換到admin用戶下,來創(chuàng)建新用戶
> use admin
switch to db admin
新建root用戶
root用戶擁有所有權(quán)限
> db.createUser({user:'Danile',pwd:'123456',roles:['root']})
Successfully added user: { "user" : "Danile", "roles" : [ "root" ] }
新建只能讀test數(shù)據(jù)庫的用戶
> db.createUser({user:'temp',pwd:'123456',roles:[{role:'read',db:'test'}]})
Successfully added user: {
"user" : "temp",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
從客戶端結(jié)束MongoDB進(jìn)程
db.shutdownServer()
使用用戶登陸MongoDB
使用認(rèn)證模式開啟MongoDB服務(wù)
> sudo mongod --auth
進(jìn)入服務(wù)后
除了登陸用戶其他操作都是不被允許的
> show dbs
2018-08-02T22:16:59.658+0800 listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
} at src/mongo/shell/mongo.js:47
登陸剛才注冊的用戶
> use admin
switched to db admin
> db.auth('Danile','123456')
1
該用戶有root權(quán)限,可以干任何事
> show dbs
admin 0.078GB
local 0.078GB
person 0.078GB
切換到temp用戶,temp用戶只被允許能夠操作test數(shù)據(jù)庫,其他事情都做不了。
> db.auth('temp','123456')
1
> show dbs
2018-08-02T22:21:14.787+0800 listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
} at src/mongo/shell/mongo.js:47