可以看到,创建的dba用户已经验证成功。接下来我在创建两个用户,验证一下其他角色权限。创建一个只读用户,一个读写用户。
> use test;
switched to db test
> db.createUser({user:"zduser",pwd:"zduser",roles:[{role:"read",db:"test"}]})
Successfully added user: {
"user" : "zduser",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
> db.createUser({user:"dxuser",pwd:"dxuser",roles:[{role:"readWrite",db:"test"}]})
Successfully added user: {
"user" : "dxuser",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
> show users;
{
"_id" : "test.zduser",
"user" : "zduser",
"db" : "test",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
{
"_id" : "test.dxuser",
"user" : "dxuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
>
在test库中创建一个集合,验证一下这两个用户权限:
> show tables;#userAdminAnyDatabase权限只针对用户管理,没有其他的权限
2017-11-17T13:47:39.845-0800 E QUERY Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on test to execute command { listCollections: 1.0 }",
"code" : 13
}
at Error (<anonymous>)
at DB._getCollectionInfosCommand (src/mongo/shell/db.js:646:15)
at DB.getCollectionInfos (src/mongo/shell/db.js:658:20)
at DB.getCollectionNames (src/mongo/shell/db.js:669:17)
at shellHelper.show (src/mongo/shell/utils.js:625:12)
at shellHelper (src/mongo/shell/utils.js:524:36)
at (shellhelp2):1:1 at src/mongo/shell/db.js:646
> exit
bye
[root@MidApp mongodb]# mongo 192.168.221.161:27000 #重新登录一下
MongoDB shell version: 3.0.6
connecting to: 192.168.221.161:27000/test
> use test
switched to db test
> db.tb1.insert({"a":1,"b":2})#先试着插入数据看看
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on test to execute command { insert: \"tb1\", documents: [ { _id: ObjectId('5a0f595b3b6523dcb81d4f76'), a: 1.0, b: 2.0 } ], ordered: true }"
}
})
> db.auth('dxuser','dxuser')#用可读写的用户认证
1
> db.tb1.insert({"a":1,"b":2})#可以插入数据
WriteResult({ "nInserted" : 1 })
> db.tb1.insert({"a":11,"b":22})
WriteResult({ "nInserted" : 1 })
> db.tb1.insert({"a":111,"b":222})
WriteResult({ "nInserted" : 1 })
> db.tb1.find()
{ "_id" : ObjectId("5a0f597f3b6523dcb81d4f77"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("5a0f59933b6523dcb81d4f78"), "a" : 11, "b" : 22 }
{ "_id" : ObjectId("5a0f59983b6523dcb81d4f79"), "a" : 111, "b" : 222 }
> db.auth('zduser','zduser')#切换只读用户
1
> db.tb1.insert({"a":1111,"b":2222})#没有权限插入数据
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on test to execute command { insert: \"tb1\", documents: [ { _id: ObjectId('5a0f59c63b6523dcb81d4f7a'), a: 1111.0, b: 2222.0 } ], ordered: true }"
}
})
> db.tb1.find()#可以查看数据
{ "_id" : ObjectId("5a0f597f3b6523dcb81d4f77"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("5a0f59933b6523dcb81d4f78"), "a" : 11, "b" : 22 }
{ "_id" : ObjectId("5a0f59983b6523dcb81d4f79"), "a" : 111, "b" : 222 }
>
注意:Mongodb用户是跟着数据库密切相关的,在哪个库授权的用户就需要去哪个库下面进行认证。
更多MongoDB相关教程见以下内容:
Linux CentOS 6.5 yum安装MongoDB