Mongodb 创建管理员帐号与普通帐号
数据库操作权限
readAnyDatabase 任何数据库的只读权限
userAdminAnyDatabase 任何数据库的读写权限
userAdminAnyDatabase 任何数据库用户的管理权限
dbAdminAnyDatabase 任何数据库的管理权限
启动客户端:
cd /usr/local/mongodb/
./mongo
查看一下用户表有没有数据
db.system.users.find()
查看用户
> show users
>
>
MongoDB创建数据库管理员用户
# 切换至admin数据库。 # 也可以使用db = db.getSiblingDB('admin')代替use admin。 use admin # 创建管理员用户,并指定其权限。 db.createUser({ user : 'root', pwd : '123456', roles : [ 'clusterAdmin', 'dbAdminAnyDatabase', 'userAdminAnyDatabase', 'readWriteAnyDatabase' ] })
输出
> db.createUser({ ... user : 'root', ... pwd : '123456', ... roles : [ ... 'clusterAdmin', ... 'dbAdminAnyDatabase', ... 'userAdminAnyDatabase', ... 'readWriteAnyDatabase' ... ] ... }) Successfully added user: { "user" : "root", "roles" : [ "clusterAdmin", "dbAdminAnyDatabase", "userAdminAnyDatabase", "readWriteAnyDatabase" ] }
重启MongoDB服务并加上--auth参数
./mongod --dbpath=/usr/local/mongodb/data --logpath=/usr/local/mongodb/logs --logappend --port=27017 --fork --auth
查看用户,会报错
> use admin switched to db admin > show users 2019-02-15T15:20:52.250+0800 E QUERY [js] Error: command usersInfo requires authentication : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DB.prototype.getUsers@src/mongo/shell/db.js:1763:1 shellHelper.show@src/mongo/shell/utils.js:859:9 shellHelper@src/mongo/shell/utils.js:766:15 @(shellhelp2):1:1
此时需要认证
> db.auth('root','123456') 1 >
查看用户,就可以看到了
> show users { "_id" : "admin.root", "user" : "root", "db" : "admin", "roles" : [ { "role" : "clusterAdmin", "db" : "admin" }, { "role" : "dbAdminAnyDatabase", "db" : "admin" }, { "role" : "userAdminAnyDatabase", "db" : "admin" }, { "role" : "readWriteAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } >
建立普通帐号
用户user
db.createUser( {user:'user', pwd:'123456', roles:[ {role:'readWrite', db:'userdb'} ] })
输出
> db.createUser( ... {user:'user', ... pwd:'123456', ... roles:[ ... {role:'readWrite', db:'userdb'} ... ] ... }) Successfully added user: { "user" : "user", "roles" : [ { "role" : "readWrite", "db" : "userdb" } ] } >
查看用户
> show users { "_id" : "admin.root", "user" : "root", "db" : "admin", "roles" : [ { "role" : "clusterAdmin", "db" : "admin" }, { "role" : "dbAdminAnyDatabase", "db" : "admin" }, { "role" : "userAdminAnyDatabase", "db" : "admin" }, { "role" : "readWriteAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } { "_id" : "admin.user", "user" : "user", "db" : "admin", "roles" : [ { "role" : "readWrite", "db" : "userdb" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } >
用户user1
db.createUser( {user:'user1', pwd:'123456', roles:[ {role:'root', db:'userdb'} ] })
接下来,为指定数据库创建一般用户角色,用于程序读取、修改数据库。
假如现有blog数据库,要为其创建用户名为admin、密码为123456,拥有CRUD(增查改删)权限,指令如下:
# 切换至blog数据库。 use blog # 创建admin用户。 db.createUser({ user : 'admin', pwd : '123456', roles : ['readWrite'] })
参考:
https://blog.csdn.net/Hu_wen/article/details/76690508
https://www.cnblogs.com/sea-stream/p/10369334.html