mongodb用户权限管理(二)

发布时间:2017-7-9 7:25:46编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"mongodb用户权限管理(二) ",主要涉及到mongodb用户权限管理(二) 方面的内容,对于mongodb用户权限管理(二) 感兴趣的同学可以参考一下。

数据库 分配用户权限

有了创建语法,和参数说明,接下来开始实践.

注意,还有一点,账号是跟着数据库绑定的,在那个库里授权,就在那个库里验证(auth)
否则会失败

创建 账号管理授权权限 的账号

> db.createUser(... {... user: 'admin',... pwd: '123456',... roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]... }... )Successfully added user: {        "user" : "admin",        "roles" : [                {                        "role" : "userAdminAnyDatabase",                        "db" : "admin"                }        ]}

然后退出数据库

> use adminswitched to db admin> db.shutdownServer()

重新启动mongodb,记得在配置文件mongod.conf里加上 auth = true

./bin/mongod -f conf/mongod.conf./bin/mongo 127.0.0.1:12345> show dbs # 没有验证,没有权限,会出错"errmsg" : "not authorized on admin to execute command> use admin> db.auth('admin', '123456')1# 返回 1 表示授权成功,0表示失败> show dbs #已经授权,可以查看了

创建 读、读写权限的账户

> use bookswitched to db book> db.createUser(... {... user: 'zhangsan',... pwd: 'zhangsan',... roles: [{role: 'read', db: 'book'}]... }... )Successfully added user: {        "user" : "zhangsan",        "roles" : [                {                        "role" : "read",                        "db" : "book"                }        ]}> db.createUser(... {... user: 'lisi',... pwd: 'lisi',... roles: [{role: 'readWrite', db: 'book'}]... }... )Successfully added user: {        "user" : "lisi",        "roles" : [                {                        "role" : "readWrite",                        "db" : "book"                }        ]}> show users{        "_id" : "book.lisi",        "user" : "lisi",        "db" : "book",        "roles" : [                {                        "role" : "readWrite",                        "db" : "book"                }        ]}{        "_id" : "book.zhangsan",        "user" : "zhangsan",        "db" : "book",        "roles" : [                {                        "role" : "read",                        "db" : "book"                }        ]}

然后验证用户权限是否正确

> db.book.insert({book: '小人书'}) # 没验证,会出错WriteResult({        "writeError" : {                "code" : 13,                "errmsg" : "not authorized on book to execute command { insert: \"book\", documents: [ { _id: ObjectId('5959b56edcc047dfe5c9b336'), book: \"小人书\" } ], ordered: true }"        }})> db.auth('lisi', 'lisi')1> db.book.insert({book: '小人书'})WriteResult({ "nInserted" : 1 })> db.auth('zhangsan', 'zhangsan') # 用户切到 zhangsan1> db.book.find() # 可以查看{ "_id" : ObjectId("5959b59fdcc047dfe5c9b337"), "book" : "小人书" }> db.book.insert({book: '择天记'}) # 没有write权限,会失败WriteResult({        "writeError" : {                "code" : 13,                "errmsg" : "not authorized on book to execute command { insert: \"book\", documents: [ { _id: ObjectId('5959b650dcc047dfe5c9b338'), book: \"择天记\" } ], ordered: true }"        }})

创建 root 超级权限账号

这个超级权限包括