非认证转模式换成认证模式数据库账号创建
1.采用admin数据库的超级管理员验证
./mongo 192.168.1.134:10001
use admin
db.auth("sa","123456")
2.创建开发用户,登陆相应的数据库创建开发用户
repltest:PRIMARY> show databases;
admin 0.078GB
db_hxl 0.078GB
db_hxl01 0.078GB
db_yeemiao 0.078GB
local 22.067GB
repltest:PRIMARY> use db_hxl --这里创建db_hxl数据库的专用账号
switched to db db_hxl
db.createUser({user:'hxl',pwd:'hxl123',roles:[{role:'dbOwner',db:'db_hxl'}]})
db.auth("hxl","hxl123")
3.退出后采用hxl账号验证
[root@localhost bin]# ./mongo 192.168.1.134:10001
MongoDB shell version: 3.0.15
connecting to: 192.168.1.134:10001/test
repltest:PRIMARY> use db_hxl
switched to db db_hxl
repltest:PRIMARY> show tables;
2019-02-20T11:24:20.682+0800 E QUERY Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on db_hxl 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
repltest:PRIMARY> db.auth("hxl","hxl123")
4.尝试写入记录
db.tb_hxl.insert( { _id: 99, type: "ttt", item: "card", qty: 15 } )
5.将其他数据库权限授权给该用户
./mongo 192.168.1.134:10001
use admin
db.auth("sa","123456")
repltest:PRIMARY> use db_hxl ##进入hxl该用户拥有的数据库
switched to db db_hxl01
repltest:PRIMARY> db.grantRolesToUser("hxl", [{ role: "readWrite", db: "db_hxl01"}])
将另外的数据库db_hxl01的读写权限赋予hxl用户
使用hxl账号登陆
[root@localhost bin]# ./mongo 192.168.1.134:10001
repltest:PRIMARY> use db_hxl
repltest:PRIMARY> db.auth("hxl","hxl123")
往刚授权的数据库写入数据
use db_hxl01
db.tb_hxl01.insert( { _id: 888, type: "ttt", item: "card", qty: 15 } )
6.查看用户的权限信息
[root@localhost bin]# ./mongo 192.168.1.134:10001
repltest:PRIMARY> use db_hxl
repltest:PRIMARY> db.auth("hxl","hxl123")
repltest:PRIMARY> db.getUsers()
[
{
"_id" : "db_hxl.hxl",
"user" : "hxl",
"db" : "db_hxl",
"roles" : [
{
"role" : "readWrite",
"db" : "db_hxl01"
},
{
"role" : "dbOwner",
"db" : "db_hxl"
}
]
}
]