默认情况下,MongoDB 不会进行身份验证,也没有账号,只要能连接上服务就可以对数据库进行各种操作,出于安全角度考虑,我们应当为其添加认证访问。本文将指导最基本的为 mongodb 副本集增加密码认证。

创建 KeyFile

副本集设置身份验证与单机不同,需要增加一个 keyFile 以便副本集成员相互认证。

这个文件需要满足下面几点要求:

  • 文本长度需要在 6 和 1024 之间
  • 认证时候不考虑文件中空白字符
  • 连接到副本集的成员和 mongos 进程的 keyfile 文件内容必须一样
  • 必须是base64编码,但是不能有等号
  • 文件权限必须是x00,也就是说,不能分配任何权限给group成员和other成员

我们可以在 Linux 上直接使用 openssl 创建一个这样的文件,然后上传至其他副本集成员服务器:

openssl rand -base64 512 > mongodb.key
chmod 400 mongodb.key

变更配置文件

请参考下面文本进行配置。

auth=true
keyFile = mongodb.key
// keyFile 可以使用绝对路径也可以使用相对路径

创建用户

创建一个全局管理员,用于管理用户:

use admin

db.createUser(
   {
     user: "root",
     pwd: "241343fjrrees",
     roles: [ "userAdminAnyDatabase" ]
   }
)

为 qiansw 库创建一个读写账户:

use qiansw

db.createUser(
   {
     user: "qiansw",
     pwd: "password",
     roles: [ "dbOwner" ]
   }
)

测试密码认证

重启 mongodb ,第一次登陆时,直接查询会报权限错误,使用 db.auth() 认证后就可以成功读取数据库了。

[root@qiansw ~]$ mongo --port 27057
MongoDB shell version: 3.2.0
connecting to: 127.0.0.1:27057/test
qiansw:PRIMARY> use qiansw
switched to db qiansw
qiansw:PRIMARY> show collections;
2017-03-06T16:47:27.792+0800 E QUERY    [thread1] Error: listCollections failed: {
    "ok" : 0,
    "errmsg" : "not authorized on qiansw to execute command { listCollections: 1.0, filter: {} }",
    "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:23:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:746:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:758:15
DB.prototype.getCollectionNames@src/mongo/shell/db.js:769:12
shellHelper.show@src/mongo/shell/utils.js:694:9
shellHelper@src/mongo/shell/utils.js:593:15
@(shellhelp2):1:1

qiansw:PRIMARY> db.auth("qiansw","password")
1
qiansw:PRIMARY> show collections;
coreUser
interfaceLogs
qiansw:PRIMARY>

更多关于权限的设置请参考 mongodb 官方文档。