【问题标题】:CRUD operation authentication for mongodbmongodb的CRUD操作认证
【发布时间】:2018-03-13 15:12:49
【问题描述】:

我正在使用 zend 3 框架和 mongodb。使用mongodb/mongodb库连接到mongodb数据库。

如何在 zend 和 mongodb 中添加验证,以便只有经过身份验证的用户才能使用 zend rest api 在 mongodb 中执行 CRUD 操作?

在 mongo shell 中,我使用以下查询向 db 添加了身份验证,效果很好。

use admin;
db.createUser(
  {
    user: "admin",
    pwd: "password",
    roles: [ { role: "root", db: "admin" } ]
  }
);
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"

use test;
db.createUser(
   {
     user: "testUser",
     pwd: "password",
     roles: [ "readWrite", "dbAdmin" ]
   }
);

db.auth("testUser", "password");

现在在 Zend 模型中,我正在使用以下代码,无需 db 身份验证即可正常工作。

$mongoClient = new \MongoDB\Client();
$collection = $mongoClient->selectDatabase($dbName)->selectCollection($collectionName);
$cursor = $collection->findOne(['_id' => $_id]);

现在如何在执行上述查询之前将用户凭据传递给\MongoDB\Client() 以验证用户身份?

【问题讨论】:

  • 你好。到目前为止,您尝试了什么?
  • @edigu,我已经用我的代码更新了问题。
  • 结果得到了准确的答案!恭喜!

标签: mongodb zend-framework3


【解决方案1】:

您可以使用以下凭据初始化客户端:

$mongoClient = new \MongoDB\Client('mongodb://username:password@host1:port');

【讨论】:

  • 如果我使用的是管理员用户而不是测试用户,它可以工作。为什么这样?还将要求第三方进行身份验证。我可以使用哪种方法来确保它在浏览器中不可见?
  • 1.您需要指定测试用户角色适用的数据库,类似于:roles: [ { role: "root", db: "admin" } ] 2. 这些凭据在 PHP 中使用不是吗?那怎么在浏览器中可见呢?
  • 如果我使用db.createUser( { user: "test", pwd: "password", roles: [ { role: "readWrite", db: "test" } ] } ); php 代码身份验证工作正常。虽然通过 mongo shell 身份验证不起作用 db.auth('test', 'password')
  • mongo --port 27017 -u "test" -p "password" --authenticationDatabase "admin" 对于测试数据库工作正常。
  • 很高兴你明白了:)
猜你喜欢
  • 2018-06-14
  • 2021-07-18
  • 2022-09-23
  • 2018-11-29
  • 2018-02-20
  • 1970-01-01
  • 2014-09-25
  • 2014-11-23
  • 1970-01-01
相关资源
最近更新 更多