Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从0开始配置带权限的Mongodb #28

Open
ChenJiaH opened this issue Aug 2, 2019 · 0 comments
Open

从0开始配置带权限的Mongodb #28

ChenJiaH opened this issue Aug 2, 2019 · 0 comments
Labels
mongodb mongodb数据库相关

Comments

@ChenJiaH
Copy link
Owner

ChenJiaH commented Aug 2, 2019

首发于微信公众号《前端成长记》,写于 2018.07.31

背景

由于数据安全问题,数据库加权限校验是必不可少的一部分。

跟传统数据库mySQL等不同的是,由于mongodb的用户名和密码是基于特定数据库的,而不是基于整个系统,所以需要对所有db进行密码设置。

步骤

前置准备

安装 mongodb 下载传送门

配置和启动数据库

打开CMD,执行下面操作

// 在安装目录的 bin 文件夹下执行// linux 需要 ./mongodb , MacOS 需要 sudo ./mongodbmongodb --dbpath 你的数据库文件夹路径

到这,能看到数据库已经成功连接。接下来,另外启动一个CMD,进行数据库操作。

// linux 需要 ./mongo , MacOS 需要 sudo ./mongo
mongo

此时可以看见 connecting to: test,表明成功。

进行用户和权限配置

  1. 首先进入 admin 数据库
use admin
  1. 创建管理员账户
db.createUser({user: "myuser", pwd: "mypwd", roles: [{role: "userAdminAnyDatabase", db: "admin"}]})

roles可选列表

  1. 验证是否成功
db.auth("myuser", "mypwd")

如果返回1,则为配置成功

重启数据库,开启授权模式

// 在安装目录的 bin 文件夹下执行
// linux 需要 ./mongodb , MacOS 需要 sudo ./mongodb
mongodb --dbpath 你的数据库文件夹路径 --auth

进行验证

show dbs

命令意思为查看数据库列表,但是因为没有经过校验,所以会报错如下:

image

auth校验

切换到admin,进行auth操作

use admin
db.auth("myuser", "mypwd")

如果返回1,则表明auth通过,此时再进行上一步的验证操作,将成功返回数据库列表。

给单独数据库配置不同权限账户

use yourdb
db.createUser({user: "youruser", pwd: "yourpwd", roles: [{role: "dbOwner", db: "yourdb"}]})

上述配置了该数据库的所有者,有该数据库的最高权限。

use yourdb
db.createUser({user: "youruser1", pwd: "yourpwd1", roles: [{role: "readWrite", db: "yourdb"}]})

上述配置了该用户对于数据库只有可读权限。

roles可选列表

结尾

至此,一个带密码校验的mongodb配置已经全部完成。Try it by yourself!

(完)


本文为原创文章,可能会更新知识点及修正错误,因此转载请保留原出处,方便溯源,避免陈旧错误知识的误导,同时有更好的阅读体验
如果能给您带去些许帮助,欢迎 ⭐️star 或 ✏️ fork
(转载请注明出处:https://chenjiahao.xyz)

@ChenJiaH ChenJiaH added the mongodb mongodb数据库相关 label Aug 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
mongodb mongodb数据库相关
Projects
None yet
Development

No branches or pull requests

1 participant