1

I am trying to connect to a mongodb database using authentication. My code for doing so is the following:

from pymongo import MongoClient
import urllib
client = MongoClient()
client = MongoClient('ip', port)
client.prod_db.authenticate('username', 'pass',  source='source_database')

However I am receiving the following error in the authentication line:

pymongo.errors.OperationFailure: Authentication failed.

Am I doing the whole authentication thing wrongly?

EDIT: Also tried to use the following schema:

client = MongoClient('mongodb://user:pass@ip:port/')

And I received the same mistake.

2 Answers 2

3

There are many reasons that may cause the Authentication to fail.

  • First check that you allow your ip for bindip. Use 0.0.0.0 to allow all clients to access the MongoServer.

  • Pass mechanism also in the authenticate() as an argument.

Something like this works for me :

client = MongoClient('127.0.0.1', 27017)
client.admin.authenticate('username', 'pass', mechanism = 'SCRAM-SHA-1', source='source_database')
db_name = client[db]
col_name = col_name
col = db_name[col_name]
Sign up to request clarification or add additional context in comments.

6 Comments

But where exactly I am adding the pass?
mechanism = 'SCRAM-SHA-1'
Are you able to authenticate in mongo shell ?
I am able to authenticate in robomongo. Didnt tried in the shell.
What is the python and mongo version ?
|
0

Typically you have to percent-escape your username and password if it has characters that need to be escaped, but the method in Satish's answer should actually allow you to not worry about that. However, if you'd like to try the percent-escaping method, as outlined in the PyMongo 3.5.1 docs, you might do that as follows (python 3):

from pymongo import MongoClient
import urllib.parse

username = urllib.parse.quote_plus('user') # username = 'user'

password = urllib.parse.quote_plus('pass/word') # password = 'pass%2Fword'

MongoClient('mongodb://%s:%[email protected]' % (username, password))

This will default to authenticating in the 'test' database. To authenticate in a specific database, do the following instead

MongoClient('mongodb://user:[email protected]/[YOUR DB]?[AUTH MECHANISM]')

For Python 2 you use "urllib.quote_plus()" to percent escape.

Comments

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.