17

I am refering to the http://api.mongodb.org/python/current/examples/authentication.html site for authentication mechanism examples. I have created a User administrator and using its credentials I created a user for my 'reporting' database. Now i need to access the same through pymongo using the username and password. I tried the following commands in python shell. Is this the right way as my authentication is failing.

from pymongo import MongoClient

client = MongoClient('localhost')

client.reporting.authenticate('reportsUser', '123456', mechanism='MONGODB-CR')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/database.py", line 746, in authenticate
    self.connection._cache_credentials(self.name, credentials)
  File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 441, in _cache_credentials
    auth.authenticate(credentials, sock_info, self.__simple_command)
  File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 214, in authenticate
    auth_func(credentials[1:], sock_info, cmd_func)
  File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 194, in _authenticate_mongo_cr
    cmd_func(sock_info, source, query)
  File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 607, in __simple_command
    helpers._check_command_response(response, None, msg)
  File "/usr/lib/python2.7/dist-packages/pymongo/helpers.py", line 147, in _check_command_response
    raise OperationFailure(msg % errmsg, code)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'reportsUser'), ('nonce', u'f8158a24f1c61650'), ('key', u'14cea216c54b93bae20acd2e076bb785')]) failed: auth failed
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
Mrunmayee
  • 495
  • 3
  • 9
  • 16
  • Did you add user ? did you start mongod in `--auth` mode ? – itzMEonTV Apr 08 '15 at 07:15
  • Enabled auth=true in the mongod.conf and restarted mongod. what else is required? – Mrunmayee Apr 08 '15 at 08:12
  • add user to database – itzMEonTV Apr 08 '15 at 08:23
  • reportsUser is the user i created for reporting database. Do i need to add it to the admin database? – Mrunmayee Apr 08 '15 at 09:17
  • No, admin database user can access all database.Can you authenticate in mongo shell ? – itzMEonTV Apr 08 '15 at 09:34
  • It worked. I realized that my users were created with SCRAM-SHA-1 as default mechanism(using mongodb 3.0.1)) and I was providing MONGODB-CR. But when I provide SCRAM-SHA-1 it gives error. May because it requires python 2.8 and i am using 2.7. So i tried the following to change the default mechanism to MONGODB-CR and it worked: use admin; db.system.version.save({ "_id" : "authSchema", "currentVersion" : 3 }) then I created users again and to check I used the following : use admin; db.system.users.find({ "credentials.MONGODB-CR" : { $exists: true}}, { user: 1, db: 1}). Thanks though :) – Mrunmayee Apr 08 '15 at 11:28
  • The user has to be created within the database. From what I can see, I assume you created the user in the admin database. – Markus W Mahlberg Apr 08 '15 at 13:30

3 Answers3

23

As an FYI, you can use the URI string format as well. The pseudocode looks like this:

pymongo.MongoClient('mongodb://user:password@server:port/')

Here's a simple connection code block with auth:

import pymongo
conn = pymongo.MongoClient('mongodb://root:pass@localhost:27017/')
db = conn['database']
coll = db['collection']

There are more options for the query string here: http://docs.mongodb.org/manual/reference/connection-string/

Hope that helps = looks like you already have it though. Happy coding!!

RandallShanePhD
  • 5,406
  • 2
  • 20
  • 30
  • 2
    Is it possible to do it in 2 steps, like, `pymongo.MongoClient(server:port/', ssl = True, ssl_keyfile ="path to private key")`, then, `auth = client.admin.authenticate(mongo_username,mongo_password)`? Is it possible to do this without passing the username, password in the URI? – Shivendra Feb 04 '16 at 15:10
  • @Shivendra : Yes, PyMongo supports two step authentication in SCRAM-SHA-1 Mode, as outlined here. http://api.mongodb.com/python/current/examples/authentication.html – kilokahn Jul 21 '17 at 09:45
  • in my case the uri should be `mongodb://root:pass@localhost:27017/databse` then get db by `db = client.get_database()` – zhuguowei Sep 11 '18 at 08:08
8

Just adding more to provided solutions.

I have been using as URI connection string and credentials being provided as f string it helps to reduce number of lines. One thing to note is about special characters in password where we convert using urllib package as shown below.

import urllib.parse
from pymongo import MongoClient

host = "localhost"
port = 27017

user_name = "myuser"
pass_word = "Pass@123"  

db_name = "mydb"  # database name to authenticate

# if your password has '@' then you might need to escape hence we are using "urllib.parse.quote_plus()" 
client = MongoClient(f'mongodb://{user_name}:{urllib.parse.quote_plus(pass_word)}@{host}:{port}/{db_name}') 
Shakeel
  • 1,869
  • 15
  • 23
1

It's worked for me.

Here you can connect mongodb to python by using authentication username and password.

import pymongo

DATABASE_NAME = "your_database_name"
DATABASE_HOST = "localhost"

DATABASE_USERNAME = "database_username"
DATABASE_PASSWORD = "database_password"

try:
    myclient = pymongo.MongoClient( DATABASE_HOST )
    myclient.test.authenticate( DATABASE_USERNAME , DATABASE_PASSWORD )
    mydb = myclient[DATABASE_NAME]

    print("[+] Database connected!")
except Exception as e:
    print("[+] Database connection error!")
    raise e

By default Mongodb uses 27017 port

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
Pranav Mundre
  • 129
  • 1
  • 5
  • Hi! I was trying this method but in some cases, ie: aws lambda, in some timeout cases, I never notice that. – omalave Oct 23 '21 at 20:20