PyMongo Auth with username and password (examples)

Updated: February 8, 2024 By: Guest Contributor Post a comment

Overview

When working with MongoDB through PyMongo in Python, a critical aspect is how to efficiently secure your data. Authentication using a username and password is a common approach to restrict access to your database. In this tutorial, we’ll cover step-by-step examples of how to implement authentication, from basic connections to more advanced configurations.

Pre-requisites

To follow along, ensure you have the following installed:

  • MongoDB server
  • Python
  • PyMongo library (you can install it using pip install pymongo)

Basic Authentication

First, let’s start with the most basic form of authentication. Assuming you have a MongoDB database running and have created a user for the database.

from pymongo import MongoClient

# Replace 'your_username', 'your_password', 'db_name' and 'localhost' with your details
client = MongoClient('mongodb://your_username:your_password@localhost/db_name')
db = client['db_name']

This example establishes a connection to the specified database using a username and password. Each component of the URI should be personalized to fit your setup.

Using Authentication Options

In the next step, we’ll dive into more precise control over the authentication process using options.

from pymongo import MongoClient

# Authentication options
client = MongoClient(
    'localhost',
    27017,
    username='your_username',
    password='your_password',
    authSource='admin',
    authMechanism='SCRAM-SHA-256'
)

This code allows you to specify the authentication source database (usually ‘admin’ for most configurations) and the authentication mechanism. While ‘SCRAM-SHA-256’ is the recommended mechanism, other options like ‘MONGODB-CR’ and ‘SCRAM-SHA-1’ are available based on your MongoDB server version.

Connection with TLS/SSL

Moving forward, securing your connection with TLS/SSL adds an extra layer of security. This is critical especially when connecting to your database over the internet. Here’s how you can achieve this:

from pymongo import MongoClient
import certifi

client = MongoClient(
    'mongodb://your_username:your_password@localhost/db_name?ssl=true&ssl_cert_reqs=CERT_OPTIONAL',
    tlsCAFile=certifi.where()
)

The parameter ssl=true enables SSL encryption for your connection. The use of certifi with the tlsCAFile option ensures that your connection is certified and secure from middle-man attacks.

Replica Set Authentication

If your MongoDB architecture is using a replica set, authentication can look a bit different. Here’s how to authenticate in such a scenario:

from pymongo import MongoClient

client = MongoClient(
    'mongodb://your_username:your_password@replicaSetHostname/?replicaSet=yourReplicaSetName',
    authSource='admin',
    authMechanism='SCRAM-SHA-256'
)

This code snippet configures the client to connect to a replica set using the specified authentication parameters. Such setups are often used for high availability and data redundancy.

Role-Based Access Control (RBAC)

If you require more granular control over who accesses what data, MongoDB’s Role-Based Access Control (RBAC) is the solution. Assigning roles to users can help restrict access to specific collections or actions. Here’s an example of how to create a user with specific roles:

# Assuming you're inside the MongoDB shell
use admin
db.createUser(
    {
        'user': 'yourUsername',
        'pwd': 'yourVeryStrongPassword',
        'roles': [
            {'role': 'readWrite', 'db': 'yourDatabaseName'},
            {'role': 'dbAdmin', 'db': 'anotherDatabaseName'}
        ]
    }
)

This illustration shows how to enforce RBAC in your MongoDB setup effectively. After creating the user with appropriate roles, you can leverage these roles when connecting with PyMongo.

Handling Connection Errors

Last but not least, efficiently handling connection errors helps to improve the robustness of your database connections. Employ exception handling in your PyMongo scripts to catch and handle exceptions gracefully.

from pymongo import MongoClient, errors

try:
    client = MongoClient('mongodb://your_username:your_password@localhost/db_name')
except errors.ConnectionFailure as e:
    print(f'Could not connect to MongoDB: {e}')

Conclusion

This tutorial has guided you through various authentication methods in PyMongo, from basic database connections to more sophisticated setups including SSL, replica sets, and RBAC. Effectively managing MongoDB authentication enhances the security and integrity of your data. Remember, correctly implementing authentication mechanisms is crucial for protecting sensitive information and ensuring data access is properly controlled.