mongodb 的 CRUD 操作认证
CRUD operation authentication for mongodb
我正在使用 zend 3 框架和 mongodb。使用 mongodb/mongodb 库连接到 mongodb 数据库。
我如何在 zend 和 mongodb 中添加验证,以便只有经过身份验证的用户才能使用 zend rest api 在 mongodb 中执行 CRUD 操作?
来自 mongo shell 我已经使用以下查询向数据库添加了身份验证,效果很好。
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 模型中,我使用以下代码,无需数据库身份验证即可正常工作。
$mongoClient = new \MongoDB\Client();
$collection = $mongoClient->selectDatabase($dbName)->selectCollection($collectionName);
$cursor = $collection->findOne(['_id' => $_id]);
现在如何将用户凭据传递给 \MongoDB\Client()
以在执行上述查询之前对用户进行身份验证?
您可以使用凭据初始化客户端,如下所示:
$mongoClient = new \MongoDB\Client('mongodb://username:password@host1:port');
我正在使用 zend 3 框架和 mongodb。使用 mongodb/mongodb 库连接到 mongodb 数据库。
我如何在 zend 和 mongodb 中添加验证,以便只有经过身份验证的用户才能使用 zend rest api 在 mongodb 中执行 CRUD 操作?
来自 mongo shell 我已经使用以下查询向数据库添加了身份验证,效果很好。
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 模型中,我使用以下代码,无需数据库身份验证即可正常工作。
$mongoClient = new \MongoDB\Client();
$collection = $mongoClient->selectDatabase($dbName)->selectCollection($collectionName);
$cursor = $collection->findOne(['_id' => $_id]);
现在如何将用户凭据传递给 \MongoDB\Client()
以在执行上述查询之前对用户进行身份验证?
您可以使用凭据初始化客户端,如下所示:
$mongoClient = new \MongoDB\Client('mongodb://username:password@host1:port');