mongodb用户权限管理-001

创建自定义用户:

  1.添加用于全局管理的角色:

db.createUser(
   {
     user: "root",
     pwd: "password",     
     roles: [{"role":"root","db":"admin"}]
   }
)

2.添加管理某一数据库的角色,可以根据需要为其添加权限,也可以之后根据需求添加权限给他:

db.createUser(
   {
     user: "username",
     pwd: "password",
     roles: [{"role":"readWrite","db":"mydb"}]
     "read"
   }
)

用户username现在具有读写mydb数据和读其他数据库的权限。

3.启用认证:

编辑mongod.conf文件为:

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
   authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

到此准备工作完成,重启mongod。

输入mongo启动客户端显示:

ongoDB shell version v4.4.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("791dd61e-6a92-449a-885e-1f5dae2d7c1e") }
MongoDB server version: 4.4.2

在客户端输入:

> use admin
switched to db admin
> show users

显示:

uncaught exception: Error: command usersInfo requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1639:15
shellHelper.show@src/mongo/shell/utils.js:914:9
shellHelper@src/mongo/shell/utils.js:819:15
@(shellhelp2):1:1

未捕获异常:错误:命令usersInfo需要身份验证:

 

继续输入:

use mydb

显示:

> use mydb
switched to db mydb
> show tables
Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus
> show Collections
uncaught exception: Error: don't know how to show [Collections] :
shellHelper.show@src/mongo/shell/utils.js:1191:11
shellHelper@src/mongo/shell/utils.js:819:15
@(shellhelp2):1:1
> show collections
Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus

警告:无法运行listCollections,试图通过分析connectionStatus来近似集合名称

 

切回use admin输入全局管理身份验证:

> use admin
switched to db admin
> db.auth("root","password")
1

显示为1,验证通过。

重复上面几个操作:

> use mydb
switched to db mydb
> show tables
depaone
> db.depaone.find()
{ "_id" : ObjectId("5fe044d5a05a6587dd767069"), "name" : "zhangsan", "age" : 23, "sex" : "msle", "wages" : 6000 }
> 

正常显示,用户权限设置成功!!

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timi先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值