blog-web/source/_posts/MongoDB/4.0、安全验证.md
结发受长生 a29cff3aed 笔记迁移
2018-05-12 19:51:10 +08:00

74 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 4.0、安全验证
date: 2018-5-12 19:24:14
tags:
- 数据库
- MongoDB
categories:
- MongoDB
---
mongoDB在默认情况下是没有开启权限认证的 , 也就是不需要用户名密码就可以连接数据库
<!-- more -->
#### 创建用户
```
db.createUser(<userinfo>)
```
其中userinfo是一个json数据 , 包含下列属性
+ user - 用户名
+ pwd - 密码
+ customData - 任意的自定义内容
+ roles : [{ role : <角色类型>, db : <数据库名称> } , … ]
一个用户可以对应多个角色 , 所以是一个数组结构
mongoDB当中内置的角色类型有
+ 数据库用户角色read、readWrite;
允许用户 读/读写 指定的数据库
+ 数据库管理角色dbAdmin、dbOwner
允许在指定数据库中执行管理函数 , 如索引增删 查看统计等
+ 用户管理角色userAdmin
允许向system.users集合写入数据, 可以在指定数据库增删用户
+ 集群管理角色clusterAdmin、clusterManager、clusterMonitor、hostManager
+ 备份恢复角色backup、restore
+ 所有数据库角色readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
可以在所有数据库中进行 读/读写/用户管理
+ 超级用户角色root
+ 内部角色__system
举例
```javascript
db.createUser({
user:"sookie",
pwd:"123456",
customData:{info:"this is my first user"},
roles:[
{role:"userAdmin",db:"admin"},
{role:"read",db:"demo"}
]
})
```
#### 开启权限认证
在配置文件中添加 ( 关于配置见前一节的内容 )
`auth=true `
重启服务即可开启数据库的权限认证
#### 认证用户
连接到mongoDB数据库以后 , 由于开启了权限认证
如果不进行用户认证 , 是没有任何权限的
![auth](/images/MongoDB/auth.png)
进行认证的步骤如下
切换到用户所在的数据库 , 比如刚才创建的用户在demo数据库下具有”read”权限
就执行`use demo`
执行`db.auth("用户名","密码")`
> **注意** 帐号是跟着库走的,所以在指定库里授权,必须也在指定库里验证(auth)
认证完成后 , 当前用户就可以执行权限所允许的操作了
---
附 : 在Robomongo当中使用指定用户访问数据库的方法
![auth](/images/MongoDB/auth_robomongo.png)