Reputation: 893
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.
Upvotes: 1
Views: 8118
Reputation: 143
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.
Upvotes: 0
Reputation: 2233
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]
Upvotes: 3