16.MongoDB 副本集安全认证

 

1.启动副本集3个节点

2.通过主节点添加一个管理员帐号

1
2
3
4
myrs:PRIMARY> use admin
switched to db admin
myrs:PRIMARY> db.createUser({ user: "myroot", pwd: "123456", roles: ["root"] })
Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }

3.创建副本集认证的key文件

(1) 生成一个key文件到当前文件夹中

1
2
3
4
[root@localhost replica_sets]# openssl rand -base64 90 -out ./mongo.keyfile
[root@localhost replica_sets]# chmod 400 ./mongo.keyfile
[root@localhost replica_sets]# ls -l
-r--------. 1 root root 122 Mar 27 05:41 mongo.keyfile

(2) 将该文件分别拷贝到每个节点中

1
2
3
[root@localhost replica_sets]# cp mongo.keyfile /mongodb/replica_sets/myrs_27017/
[root@localhost replica_sets]# cp mongo.keyfile /mongodb/replica_sets/myrs_27018/
[root@localhost replica_sets]# scp mongo.keyfile root@192.168.76.132:/mongodb/replica_sets/myrs_27019/

4.修改配置文件指定keyfile

1
2
3
[root@localhost bin]# vim /mongodb/replica_sets/myrs_27017/mongod.conf
[root@localhost bin]# vim /mongodb/replica_sets/myrs_27018/mongod.conf
[root@localhost bin]# vim /mongodb/replica_sets/myrs_27019/mongod.conf

添加配置

1
2
3
4
5
security:
# KeyFile鉴权文件
keyFile: /mongodb/replica_sets/myrs_27017/mongo.keyfile
# 开启认证方式运行
authorization: enabled

5.重新启动副本集

6.在主节点上添加普通账号

1
2
3
4
5
6
7
8
9
10
11
12
13
# 先用管理员账号登录
# 切换到admin库
myrs:PRIMARY> use admin
switched to db admin
# 管理员账号认证
myrs:PRIMARY> db.auth("myroot", "123456")
1
# 切换到要认证的库
myrs:PRIMARY> use articledb
switched to db articledb
# 添加普通用户
myrs:PRIMARY> db.createUser({user: "denial", pwd: "123456", roles: ["readWrite"]})
Successfully added user: { "user" : "denial", "roles" : [ "readWrite" ] }

7.使用普通用户重新登录,查看数据

1
2
3
4
5
6
7
8
9
10
11
myrs:PRIMARY> use articledb
switched to db articledb
myrs:PRIMARY> db.auth("denial", "123456")
1
myrs:PRIMARY> db.comment.count()
4
myrs:PRIMARY> db.comment.find()
{ "_id" : ObjectId("641cc67ab8fd97e6b05dd3bd"), "articleid" : "100000", "content" : "今天天气真好,阳光明媚", "userid" : "1001", "nickname" : "Rose", "createdatetime" : ISODate("2023-03-23T21:36:58.736Z") }
{ "_id" : "1", "articleid" : "100001", "content" : "morning", "userid" : "1002", "nickname" : "lake", "createdatetime" : ISODate("2019-08-05T22:08:15.522Z"), "likenum" : 1000, "state" : "1" }
{ "_id" : ObjectId("641d5cc9546c2d2c0c5361b5"), "articleid" : "100002", "content" : "afternoon" }
{ "_id" : ObjectId("641d60da546c2d2c0c5361b7"), "articleid" : "100003", "content" : "evening" }

8.SpringDataMongoDB连接认证

application.yml

1
2
3
4
spring:
data:
mongodb:
uri: mongodb://denial:123456@192.168.76.128:27017,192.168.76.128:27018,192.168.76.132:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

9.Compass 连接认证