1. 不已认证方式启动数据库
# mongod
2.在admin数据库下创建管理test数据库的用户root
> use admin
switched to db admin
> db.createUser(
... {
... user: "root",
... pwd: "redhat",
... roles:
... [
... {
... role: "dbOwner",
... db: "test"
... }
... ]
... }
... )
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "dbOwner",
"db" : "test"
}
]
}
> db.system.users.find()
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "MONGODB-CR" : "7f3787d10c356c844000a4109c298d95" }, "roles" : [ { "role" : "dbOwner", "db" : "test" } ] }
>
3.关闭数据库然后以认证方式启动
# mongod -auth
4.通过刚才创建的账号登录到admin
# mongo --port 27017 -u root -p redhat --authenticationDatabase admin
MongoDB shell version: 2.6.4
connecting to: 127.0.0.1:27017/test
> show collections
inventory
person
system.indexes
> db.auth("root","redhat")
Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } //这里和第5步的错误一样的道理
0
> db.person.find()
{ "_id" : ObjectId("543486df137d8f2e44e8892b"), "name" : "ran", "age" : 26, "status" : "A", "groups" : [ "news", "sports" ] }
{ "_id" : ObjectId("54348713137d8f2e44e8892c"), "name" : "ry", "age" : 16, "status" : "D", "groups" : [ "new", "ss" ] }
{ "_id" : ObjectId("5434880a137d8f2e44e8892d"), "name" : "ran", "age" : 36, "status" : "A", "groups" : [ "news", "sports" ] }
{ "_id" : ObjectId("54348812137d8f2e44e8892e"), "name" : "ran", "age" : 46, "status" : "A", "groups" : [ "news", "sports" ] }
> use admin
switched to db admin
> show collections
2014-10-28T09:56:56.848+0800 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131 //因为创建的用户对admin数据库没有管理的权限,
5.通过刚才创建的账号登录到test
# mongo --port 27017 -u root -p redhat --authenticationDatabase test
MongoDB shell version: 2.6.4
connecting to: 127.0.0.1:27017/test
2014-10-28T09:32:07.805+0800 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1210
exception: login failed //这里报错了
总结:
1.上面的用户是在admin数据库下面创建的,但创建的用户对test数据库有管理权限,由于mongod的认证是首先去比对你要认证的数据库是不是有此用户,所以第5步和第4步的认证都会报错.
2.因为是在admin数据库下创建的所以要管理test数据库得必须得先认证admin,先到admin报道才能去管理test数据库。
3.如果想直接认证test数据库来登录管理test 比如
# mongo --port 27017 -u root -p redhat --authenticationDatabase test
那么创建用户的时候必须切换到test数据库下去创建(use test)。
4.如果看不懂就动手测试下就明白啦。
用户管理实验-认证
最新推荐文章于 2022-08-31 23:33:10 发布