如何配置MongoDB 3.x/4.x身份验证

时间:2020-02-23 14:30:27  来源:igfitidea点击:

我知道很多人都习惯于在没有身份验证的情况下运行MongoDB。
如果我们尝试了Lynis或者Nessus安全审核,我们可能会出现警告"不曼德布授权"。
让我们介绍如何为MongoDB中的用户/数据库设置身份验证。

当Mongod服务正在运行时,请使用使用 mongo命令行工具

# mongo --port 27017

然后用"root"角色创建用户帐户以成为数据库管理员。

> use testdb;
switched to db testdb
> db.createUser(
  {
    user: "dbadmin",
    pwd: "StrongPassword",
    roles: [ { role: "root", db: "admin" } ]
  }
)
> exit
bye

打开文件 /etc/mongod.conf并启用身份验证

security:
  authorization: enabled

重启MongoDB.

sudo systemctl restart mongod

通过连接测试 testdb作为 dbadmin用户。

mongo --port 27017 -u "dbadmin" -p --authenticationDatabase "testdb"

当被要求输入密码时,输入我们设置的密码。

MongoDB shell version v4.0.2
Enter password: 
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.0.2
Server has startup warnings: 
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-09-11T22:02:40.821+0000 I CONTROL  [initandlisten] 
--
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB Jan use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
--
>

我们现在有一个工作的MongoDB身份验证,让用户访问特定数据库。