创建自定义用户:
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 }
>
正常显示,用户权限设置成功!!