1. 开启权限认证(用户密码登录)
MongoDB默认不启用授权认证,只要能连接到该服务器,就可连接到mongod。若要启用安全认证,需要更改配置文件mongdb.conf中的参数auth。
MongoDB的用户是跟数据库相关联的,具体的数据库,需要有对应的用户,超级管理员也不能操作其他数据库的。
MongoDB存储所有的用户信息在admin 数据库的集合system.users中,保存用户名、密码和数据库信息。
MongoDB开启权限认证:配置用户名和密码认证登录,操作步骤:
1、创建mongo 用户并设置密码
- 1、为admin数据库创建管理员账号
mongo 命令在MongoDB 安装路径的bin路径下
./mongo
use admin
db.createUser({user:"root",pwd:"exmple_pwd",roles:["root"]})
2、查看目前用户
show users
1.2、为数据库mytest创建普通用户
1、给数据库mytest创建cg用户
use mytest
db.createUser({user:"cg",pwd:"lianshi",roles:[{role:"readWrite",db:"mytest"}]})
2、查看目前用户
show users
# 查看新创建的用户
db.system.users.find()
2、查看是否开启认证登录
查看mongodb.cfg
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: H:\MongoDB\data
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: H:\MongoDB\log\mongod.log
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
#processManagement:
security:
authorization: enabled
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
- 修改 authorization: enabled
3. 重启mongo服务
- win:
直接在任务管理器的服务中找到mongo 服务重启
- linux:
ps -ef |grep mongo
kill -9 15231
./mongod -f mongodb.conf
4. 登陆mongo验证
- 登陆mongo 命令行操作
./mongo
use admin
show users
此时,显示如下:
2020-06-21T20:14:59.735+0800 E QUERY [js] uncaught exception: Error: command usersInfo requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1638:15
shellHelper.show@src/mongo/shell/utils.js:883:9
shellHelper@src/mongo/shell/utils.js:790:15
@(shellhelp2):1:1
授权配置并重启后,此时查看用户,会发现没有权限
- db.auth("root","exmple_pwd")
使用db.auth(“root”,”lianshi”)启用auth认证,看到返回的值为1,这就表示启动成功了,然后我们再使用命令查看用户和数据库。