MongoDB运维实战

mongoDB(四) mongoDB认证

2020-04-09  本文已影响0人  Starlightskm

mongoDB认证

单节点认证

[root@centos7-node4 ~]# vim /data/mongodb/27017/mongodb.conf 
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/27017/mongodb.log
storage:
  dbPath: /data/mongodb/27017/
  journal:
    enabled: true
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 0.0.0.0
security:
  authorization: enabled
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongod -f /data/mongodb/27017/mongodb.conf   #启动服务
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongo 127.0.0.1:27017
> use test
switched to db test
> db.mydata.insert({id:1})
WriteCommandError({
        "ok" : 0,
        "errmsg" : "not authorized on test to execute command { insert: \"mydata\", ordered: true, lsid: { id: UUID(\"84740c59-f4ff-4fe5-879d-d10679b0f355\") }, $db: \"test\" }",
        "code" : 13,
        "codeName" : "Unauthorized"
})
> 
> use admin
> db.createUser({
... user: "admin",
... pwd: "qwer1234QAZ",
... roles: [ { role: "root",db: "admin" } ]
... })
> use admin
> db.auth('admin','qwer1234QAZ')
> use test
> db.mydata.insert({id:"1"})     #插入数据测试
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongo 127.0.0.1:27017 -uadmin -pqwer1234QAZ --authenticationDatabase admin

副本集认证

证书准备

[root@centos7-node4 ~]# openssl rand -base64 756 > /data/mongodb/cluster.key
[root@centos7-node4 ~]# chmod 700 /data/mongodb/cluster.key

环境说明

三台副本集机器,设置好各自的端口:27017,27018,27019
我这边先用单节点三副本配置: 其余的配置文件改成对应端口和目录即可

[root@centos7-node4 ~]# mkdir /data/mongodb/{27017,27018,27019} -pv 
[root@centos7-node4 ~]# vim /data/mongodb/27017/mongodb.conf 
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/27017/mongodb.log
storage:
  dbPath: /data/mongodb/27017/
  journal:
    enabled: true
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 0.0.0.0
replication:
  replSetName: cluster
security:
  keyFile: /data/mongodb/cluster.key
  authorization: enabled
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongod -f /data/mongodb/27017/mongodb.conf 
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongod -f /data/mongodb/27018/mongodb.conf 
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongod -f /data/mongodb/27019/mongodb.conf 
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongo 127.0.0.1:27017
> use admin
> config = { _id:"cluster", members:[ {_id:0,host:"127.0.0.1:27017"}, {_id:1,host:"127.0.0.1:27018"}, {_id:2,host:"127.0.0.1:27019"}] }
> rs.initiate(config)    # 初始化
cluster:SECONDARY> rs.status()
cluster:PRIMARY> use admin
cluster:PRIMARY> db.createUser({
... user: "admin",
... pwd: "qwer1234QAZ",
... roles: [ {role: "root",db:"admin"} ]
... })

> use admin
> db.auth('admin','qwer1234QAZ')
> use test
> db.mydata.insert({id:"1"})   
[root@centos7-node4 ~]# /usr/local/mongodb/bin/mongo 127.0.0.1:27017 -uadmin -pqwer1234QAZ --authenticationDatabase admin

分片配置认证

上一篇下一篇

猜你喜欢

热点阅读