mongoengine 使用身份验证数据库

mongoengine using Authentication Database

我不确定如何连接到 mongodb 数据库,该数据库使用带有 mongoengine 的身份验证数据库。

在命令提示符下,我需要执行 mongo hostname:27017/myApp -u "test" -p "test" --authenticationDatabase admin,但我看不到将其作为参数传递给 mongoengine 的位置,因此我使用 admin 数据库进行身份验证,但连接到 myApp 数据库对于我的模型?

我相信这是 PyMongo 指南中的解释:

https://api.mongodb.com/python/current/examples/authentication.html

>>> from pymongo import MongoClient
>>> client = MongoClient('example.com')
>>> db = client.the_database
>>> db.authenticate('user', 'password', source='source_database')

我找到了将其添加到 mongoengine 的拉取请求:

https://github.com/MongoEngine/mongoengine/pull/590/files

看起来您只是将 authentication_source 作为参数添加到 connect,就像 connect(authentication_source='admin') 一样。如果有更好的文档记录就好了。

http://docs.mongoengine.org/apireference.html?highlight=authentication_source

根据 mongoengine connecting guideconnect() 方法支持 URI 样式连接。即

connect(
   'project1'
   host='mongodb://username:password@host1:port1/databaseName'
)

从这个意义上讲,您还可以指定身份验证源数据库,如下所示:

"mongodb://username:password@host1:port1/database?authSource=source_database"

有关更多 MongoDB URI 示例,另请参阅 MongoDB connection string URI。 还有Authentication options through connection string

建议的解决方案对我不起作用。什么工作: 只需将 authSource 参数添加到 connect 方法,就像使用 pymongo MongoClient 方法一样。示例:

connect('database_name', host='host', username="username", 
password="password",authSource='authentication_database_name') 

API已经更新,现在正确的做法是:

connect('mydb',
        host="localhost",
        username="admin",
        password="secret",
        authentication_source='your_auth_db')

这是一个对我有用的简单解决方案。

connect(db="database_name", host="localhost", port=27017, username="username", 
password="password", authentication_source="admin")