MongoDB的身份验证

1、当开启了安全检查之后,只有通过身份认证的用户才能进行数据的读写操作
2、admin和local是两个特殊的数据库,它们当中的用户可对任何数据库进行操作
3、经认证后,管理员用户可对任何数据库进行读写操作,同时能执行只有管理员才能执行的命令
4、在开启了安全检查的数据库启动前,应至少添加一个管理员用户
5、db.createUser()
在当前数据库中创建一个新用户,如果用户已经存在了则抛出异常
db.createUser(user, writeConcern)的参数:
user文档结构:
{
user: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
authenticationRestrictions: [
{
clientSource: ["<IP>" | "<CIDR range>", ...]
serverAddress: ["<IP>" | "<CIDR range>", ...]
},
...
],
mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ],
passwordDigestor: "<server|client>"
}

6、样例1,创建普通用户:
> use member
switched to db member
> db.createUser(
... {
... user: "member",
... pwd: "password",
... roles: [ "readWrite"]
... }
... );
Successfully added user: { "user" : "member", "roles" : [ "readWrite" ] }
>

7、样例2,创建管理员用户:
> use admin
switched to db admin
> db.createUser(
... {
... user: "root",
... pwd: "root",
... roles: ["dbAdmin"]
... }
... );
Successfully added user: { "user" : "root", "roles" : [ "dbAdmin" ] }
>

8、开启省份验证
在mongo.conf里面增加配置:
security:
authorization: enabled
9、登录看看:
[mongodb]$ bin/mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
> show dbs
2018-07-13T11:38:27.119+0800 E QUERY [js] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "command listDatabases requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1
shellHelper.show@src/mongo/shell/utils.js:865:19
shellHelper@src/mongo/shell/utils.js:755:15
@(shellhelp2):1:1
>
10、验证登录:
> db.auth("member","password");
1
> db.getCollectionNames()
[ ]
>

猜你喜欢

转载自blog.csdn.net/duzm200542901104/article/details/81029007