This section demonstrates how to establish a secure connection to a MongoDB instance using PyMongo, incorporating authentication. Proper authentication is crucial for protecting your database from unauthorized access.
The primary method for connecting with authentication involves providing credentials directly to the MongoClient. This example uses the SCRAM-SHA-256 authentication mechanism, which is a recommended secure option.
# https://pymongo.readthedocs.io/en/stable/examples/authentication.html?highlight=authentication
# example server:
# - https://github.com/ruanbekker/cheatsheets/blob/master/mongodb/python/docker/docker-compose.yml
from pymongo import MongoClient
# Establish connection with username, password, authSource, and authMechanism
client = MongoClient("192.168.0.8:27017", username="root", password="pass", authSource="admin", authMechanism="SCRAM-SHA-256")
# Verify connection by listing database names
print(client.list_database_names())
Alternatively, you can construct a MongoDB connection URI string that includes the authentication details. This is often a more concise way to manage connection parameters.
# Constructing the connection URI with authentication details
uri = "mongodb://root:[email protected]:27017/?authSource=admin&authMechanism=SCRAM-SHA-256"
client = MongoClient(uri)
# Verify connection by listing database names
print(client.list_database_names())
- username: The username for authentication.
- password: The password associated with the username.
- authSource: The database where the user is defined (often "admin" for administrative users).
- authMechanism: The authentication mechanism to use (e.g., "SCRAM-SHA-256", "MONGODB-CR").