Jzbach
Jzbach

Reputation: 368

PyMongo authentication with docker

I'm having some problems to authenticate a newly created user in MongoDB. My setup is the MongoDB 4.4.2 in a container and python 3.8.

I have created a user as follows:

from pymongo import MongoClient

host = "mongodb://root_user:[email protected]:27017"
DB_NAME = "test"
client = MongoClient(host)
test_db = client[DB_NAME]
test_db.command("createUser", "TestUser", pwd="TestPwd", roles=["readWrite"])

So far, so good: I simply added the TestUser to the database test, and so I see when I query the collection client.system.users.find({'user': 'TestUser'}), I get the test user with db: test.

Now if I want to test this user connection with

host = "mongodb://TestUser:[email protected]:27017"

it shows an authentication failure: pymongo.errors.OperationFailure: Authentication failed.

I can connect via the shell inside the container but not via pymongo and I tried already to connect specifying the authentication method, the authentication database and neither worked so far.

Any hints would be much appreciated!

Upvotes: 0

Views: 856

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

Two issues.

  1. As the commenter notes, you are creating the user in the test database; by default MongoDB will look for credentials in the admin database if authSource is not specified. Therefore you will need to append /<optional database name>?authSource=test to your connection string.

  2. You create your account with password TestPwd, but on the connection string you have testPwd; so this won't authenticate.

So, assuming your password is definitely TestPwd, your connection string should be:

mongodb://TestUser:[email protected]:27017/test?authSource=test

Upvotes: 2

Related Questions