auth_make_connection
Learn how to make a MongoDB connection with authentication using PyMongo. This guide provides Python code examples for secure database access.
MongoDB Authentication: Make Connection
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.
Connecting with Username and Password
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())
Connecting via MongoDB Connection URI
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:pass@192.168.0.8:27017/?authSource=admin&authMechanism=SCRAM-SHA-256"
client = MongoClient(uri)
# Verify connection by listing database names
print(client.list_database_names())
Key Authentication Parameters
- 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").