Unable to connect to my MongoDB Atlas using pymongo

I’m struggling with this since yesterday, when I get my credentials from an external file, it becomes unable to authenticate, it shows this error:

pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}

I tried to get my credentials from sqlite3, it didn’t work, i thought it was just a problem with sqlite, so I tried to do the same and store my credentials in a config file (.ini), and it doesn’t work either,
Even if I print the connection url, it is 100% correct, exactly the same I use when typing it manually and works.

Any thoughts on this ?

Forgot to give an example of the code I use

        # Get the MongoDB credentials from the config file
        cparser = ConfigParser()
        USERNAME = quote_plus(cparser["MONGODB"]["USERNAME"])
        PASSWORD = quote_plus(cparser["MONGODB"]["PASSWORD"])
        CLUSTER = cparser["MONGODB"]["CLUSTER"]

        # Preparing the database URL
        uri = f'mongodb+srv://{USERNAME}:{PASSWORD}@{CLUSTER}/test?authSource=admin&replicaSet=atlas-itbq89-shard-0&readPreference=primary&ssl=true'

        # Connecting to the MongoDB database
        self.client = MongoClient(uri)

Hi @Abdel and welcome to the MongoDB Community forums! :wave:

Does your password happen to have a special character in it? If so you will want to URL encode that value.

Hi @Doug_Duncan
Thank you for your response, but my password doesn’t have any special character, and even further, I already used the quote_plus() function that encode the username and password in case they contain any special character…

Well then, since it’s an authentication error, I would verify that the username and password in the config file are indeed correct by trying to connect with the mongosh shell (or the older mongo tool if you installed 5.0 or older).

 urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)¶

@Abdel are you providing a value for the encoding= kwarg?

@Jack_Woehr No, I am only passing the username/password directly to the quote_plus() function as shown in the example