0

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!

2
  • 1
    It's unclear which database you're authenticating against. You can set your authenticationDatabase by using authSource=test. Which brings your URI to mongodb://TestUser:[email protected]:27017/?authSource=test. As per the docs: docs.mongodb.com/manual/reference/connection-string Commented Dec 20, 2020 at 5:42
  • Oh man, I was setting all the time authSource=system in my experiments becuase it is in system.users where this entry exists, but I completely missed the point that the authSource is the database to which I try to connect to. Thank you very much @RobertSeaman Commented Dec 20, 2020 at 10:39

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, I re-wrote the other connection string instead of copy-paste it. My bad! In your answer, tho, I think you meant port 27017, not 27019.
oh yeah sorry 27017 - edited it. Glad you got it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.