MongoDB学习札记 第二篇 mongodb安全
mongodb安全
要开启mongodb的安全认证,在mongod服务启动的时候需要指定 –auth 参数,用来表示开启安全认证
> mongod --auth
开启之后,在通过客户端连接,虽然可以连接上,但是无法操作
G:\JavaData\mongoDB\bin>mongo
MongoDB shell version: 2.6.3
connecting to: test
> show collections
2015-06-05T20:10:51.608+0800 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
>
根据提示,我们知道出错原因是没有认证、
切换到admin这个数据库,添加用户。创建用户的语法如下
db.createUser({
user:"username",
pwd:"password",
customData:{any info},
roles:[{role:"<role>",db:"<db>"},{role:"<role>",db:"<db>"}]
})
其中mongodb内建的角色: read, readWrite, dbAdmin, dbOwner, userAdmin,dbAdminAnyDatabase,userAdminAnyDatabase,readWriteAnyDatabase,readAnyDatabase,clusterAdmin
在我们的例子中,我们通过如下语句为demo这个数据库创建 lwb 用户,并且只具备读的权限
> db.createUser({user:"lwb",pwd:"lwb",roles:[{role:"read",db:"demo"}]})
Successfully added user: {
"user" : "lwb",
"roles" : [
{
"role" : "read",
"db" : "demo"
}
]
}
> db
demo
通过命令 db.auth("lwb","lwb")
来认证
> use demo
switched to db demo
> show collections
2015-06-05T20:31:15.034+0800 error: {
"$err" : "not authorized for query on demo.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
> db.auth("lwb","lwb")
1
> show collections
system.indexes
users
> db.users.find()
{ "_id" : ObjectId("55717fd5e25992bae59cca66"), "username" : "saveMethod", "pwd" : "9999" }
查看的认证已经可以了,但是我们指定的是read的权限,所以,我们需要测试一下是否可以插入数据
> db.users.insert({username:'abc'})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on demo to execute command { insert: \"users\", documents: [ { _id: ObjectId('557196b2e661d1419e528fbb'), username: \
"abc\" } ], ordered: true }"
}
})
>
可以观察到,认证失败。说明我们的lwb用户不能像demo这个数据库的users集合插入数据
为了形成对比,我们在插入一个用户 rwu (read write user) 并让这个用户具备 readWrite权限。
> use admin
switched to db admin
> db.auth("admin","admin")
1
> db.createUser({user:"rwu",pwd:"rwu",roles:[{role:"readWrite",db:"demo"}]})
Successfully added user: {
"user" : "rwu",
"roles" : [
{
"role" : "readWrite", //具备 读写 权限
"db" : "demo" //针对 demo这个数据库的 读写 权限
}
]
}
> use demo
switched to db demo
> show collections
system.indexes
users
> db.users.find()
{ "_id" : ObjectId("55717fd5e25992bae59cca66"), "username" : "saveMethod", "pwd" : "9999" }
> db.users.save({username:"rwu",pwd:"rwu"}) //插入一条数据,插入成功表示授权成功
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("55717fd5e25992bae59cca66"), "username" : "saveMethod", "pwd" : "9999" }
{ "_id" : ObjectId("557198f5e661d1419e528fbc"), "username" : "rwu", "pwd" : "rwu" }
>
通过上面你的观察, 我们发现了创建的新用户 rwu 具有 readWrite权限后,可以往demo数据库的users集合插入数据了。
权限讲解至此。更多详细内容参考mongodb的anual文档。
转载请注明出处! 原文地址: http://webinglin.github.io