2

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.

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
  • try connecting with the mongo server manually using the same credentials, you may use mongo shell for that. – Shashank Aug 17 '17 at 10:42
  • @Shashank I can connect manually to mongo server with the same credentials, but my goal is to connect to mongo using `pymongo` –  Aug 17 '17 at 10:54
  • Have you tried these solutions: 1. https://stackoverflow.com/questions/40346767/pymongo-auth-failed-in-python-script 2. https://stackoverflow.com/questions/36200288/mongolab-pymongo-connection-error 3. https://stackoverflow.com/questions/23682933/python-pymongo-auth-failed – Shashank Aug 17 '17 at 12:40
  • Try adding `/your-db-name` to the `host`, that worked for me. – radtek Jul 10 '18 at 15:20

3 Answers3

7

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

Nathan
  • 541
  • 5
  • 6
  • This worked for me connecting to MongoDB (AWS EC2) from a Flask instance (AWS ECS) on the same VPC with security inbound rules set for MongoDB to accept from the ECS security group. – autry.richard Nov 07 '21 at 23:20
5

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

Sabuhi Shukurov
  • 1,616
  • 16
  • 17
  • 1
    An underrated answer. You solved my problem ! To give a bit of context: I am using Docker as container to create the service and connection with mongodb. I had to pull new changes form a github repo, re-configured dockercompose.yml. Then, I wanted to reconnect with same credentials I've done before and for some reason I had this issue. Apparently, for some reason, this reconfiguration deleted my previous user, and now I wanted to reconnect with same credentials and the user was not found. I created the user like you explained, and it worked like charm ! Thanks mate ! – geekt Jul 16 '22 at 12:51
0

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