Sling Academy
Home/Python/PyMongo Auth with username and password (examples)

PyMongo Auth with username and password (examples)

Last updated: February 08, 2024

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.

Next Article: PyMongo: How to save and query ISODate

Previous Article: PyMongo: How to connect to a remote MongoDB server

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types