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

时间:2020-02-23 14:38:21  来源:igfitidea点击:

我知道许多人习惯于不进行身份验证就运行MongoDB。如果尝试Lynis或者Nessus安全审核,则可能会收到有关No MongoDB授权的警告。让我们介绍如何在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

通过以dbadmin用户身份连接到testdb进行测试。

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身份验证,以便用户访问特定的数据库。