mongoengine using Authentication Database
Asked Answered
S

4

7

I am not sure how to connect to a mongodb database that uses an authentication database with mongoengine.

On the command prompt I need to do mongo hostname:27017/myApp -u "test" -p "test" --authenticationDatabase admin, but I don't see where I'd pass this as an argument to mongoengine so I use the admin database for auth but connect to the myApp database for my models?

I believe this is where it's explained in the PyMongo guide:

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')

and I found the pull request that added this to mongoengine:

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

It looks like you just add authentication_source as an argument to connect like connect(authentication_source='admin'). It'd be nice if it was better documented.

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

Sealey answered 6/11, 2016 at 1:6 Comment(0)
E
9

According to the mongoengine connecting guide, the connect() method support URI style connections. i.e.

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

In that sense, you can also specify the authentication source database as below:

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

See also MongoDB connection string URI for more MongoDB URI examples. Also Authentication options through connection string

Estrin answered 9/11, 2016 at 23:37 Comment(2)
this isn't what I'm asking, the authentication source needs to be explicitly stated and so what you sent won't workSealey
@Sealey updated. I've extracted the information out of the link which let's you specify authentication source via the URI.Estrin
S
5

The API has been updated, so this is the right way to do it now:

connect('mydb',
        host="localhost",
        username="admin",
        password="secret",
        authentication_source='your_auth_db')
Shlomo answered 21/4, 2020 at 16:30 Comment(1)
I believe the API has been updated since I asked this question back in 2016, could you indicate that in your answer?Sealey
C
2

The solution suggested doesn't work for me. What does work: just add a authSource argument to the connect method as you would do with pymongo MongoClient method. Example:

connect('database_name', host='host', username="username", 
password="password",authSource='authentication_database_name') 
Capriccio answered 12/10, 2017 at 7:15 Comment(0)
H
1

Here is an easy solution that worked for me.

connect(db="database_name", host="localhost", port=27017, username="username", 
password="password", authentication_source="admin")
Hartzel answered 14/7, 2021 at 4:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.