user7702253
user7702253

Reputation:

Authentication failed to connect to mongodb using pymongo

We have written a piece of code in python script using pymongo that connects to mongodb.

username = 'abc'
password = 'xxxxxx'
server = 'dns name of that server'
port = 27017

In program, the code looks like:

import pymongo
from pymongo import MongoClient
client = MongoClient(url, serverSelectionTimeoutMS=300)
database = client.database_name
data_insert = database.collection_name.insert_one({'id': 1, 'name': xyz})

When I tried to do these operations, it raises an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
    exhaust)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 99, in send_message_with_response
    with self.get_socket(all_credentials, exhaust) as sock_info:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 168, in get_socket
    with self.pool.get_socket(all_credentials, checkout) as sock_info:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 792, in get_socket
    sock_info.check_auth(all_credentials)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 512, in check_auth
    auth.authenticate(credentials, self)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 470, in authenticate
    auth_func(credentials, sock_info)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 450, in _authenticate_default
    return _authenticate_scram_sha1(credentials, sock_info)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 201, in _authenticate_scram_sha1
    res = sock_info.command(source, cmd)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 419, in command
    collation=collation)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 116, in command
    parse_write_concern_error=parse_write_concern_error)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 210, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.

In MongoDB, while performing queries we are getting the responses normally, without raising any errors.

Upvotes: 3

Views: 12674

Answers (3)

Michael Edwards
Michael Edwards

Reputation: 1

I ran into this error, and my problem was with the password.

I had what I believe to be a special character in the Master account. Changing the password to be only alphanumeric fixed it for me.

Code snippet

client = pymongo.MongoClient(
        'mongodb://username:alphaNumericPassword@localhost:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'
    )

    # Specify the database to be used
    db = client['prod-db']

Upvotes: 0

nathan lile
nathan lile

Reputation: 641

Because the other answers to your question didn't work for me, I'm going to copy and paste my answer from a similar question.

If you've tried the above answers and you're still getting an error:

pymongo.errors.OperationFailure: Authentication failed.

There's a good chance you need to add ?authSource=admin to the end of your uri.

Here's a working solution that I'm using with MongoDB server version 4.2.6 and MongoDB shell version v3.6.9.

from pymongo import MongoClient

# Replace these with your server details
MONGO_HOST = "XX.XXX.XXX.XXX" 
MONGO_PORT = "27017"
MONGO_DB = "database"
MONGO_USER = "admin"
MONGO_PASS = "pass"

uri = "mongodb://{}:{}@{}:{}/{}?authSource=admin".format(MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB)
client = MongoClient(uri)

Similar fix for command line is adding --authenticationDatabase admin

Upvotes: 7

Sabuhi Shukurov
Sabuhi Shukurov

Reputation: 1920

Well, I have been stuck with the same error for almost 3-4 hours. I came across solution with the following steps:

from your shell connect to MongoDB by typing: mongo

afterwards, create a database: use test_database

Now create a user with the following command with readWrite and dbAdmin privileges.

db.createUser(
   {
     user: "test_user",
     pwd: "testing12345",
     roles: [ "readWrite", "dbAdmin" ]
   }
);

This will prompt Successfully added user: { "user" : "test_user", "roles" : [ "readWrite", "dbAdmin" ] }

you can check by typing: show users. It will also show you DB name you created before in the json.

now you should be able to insert data to your database:

client = MongoClient("mongodb://test_user:myuser123@localhost:27017/test_database")
db = client.test_database

data = {"initial_test":"testing"}
db["my_collection"].insert_one(data).inserted_id

Upvotes: 5

Related Questions