Docs Home → Develop Applications → Python Drivers → PyMongo
Enterprise Authentication Mechanisms
On this page
Overview
MongoDB Enterprise Edition includes authentication mechanisms that aren't available in MongoDB Community Edition. In this guide, you can learn how to authenticate to MongoDB by using these authentication mechanisms. To learn about the other authentication mechanisms available in MongoDB, see Authentication Mechanisms.
Kerberos
The Generic Security Services API (GSSAPI) provides an interface for Kerberos authentication. Select the tab that corresponds to your operating system to learn how to use Kerberos to authenticate.
First, use pip or easy_install to install the Python kerberos or pykerberos module.
After installing one of these modules, run the kinit
command to obtain and cache
an initial ticket-granting ticket. The following example uses the
knit
command to obtain a ticket-granting ticket for the principal
mongodbuser@EXAMPLE.COM
. It then uses the klist
command to display the principal and ticket in the credentials cache.
kinit mongodbuser@EXAMPLE.COM mongodbuser@EXAMPLE.COM's Password: klist Credentials cache: FILE:/tmp/krb5cc_1000 Principal: mongodbuser@EXAMPLE.COM Issued Expires Principal Feb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/mongodbuser@EXAMPLE.COM
After you obtain a ticket-granting ticket, set the following connection options:
username
: The Kerbos principal to authenticate. Percent-encode this value before including it in a connection URI.authMechanism
: Set to"GSSAPI"
.authMechanismProperties
: Optional. By default, MongoDB usesmongodb
as the authentication service name. To specify a different service name, set this option to"SERVICE_NAME:<authentication service name>"
.
You can set these options in two ways: by passing arguments to the
MongoClient
constructor or through parameters in your connection string.
client = pymongo.MongoClient("mongodb://<hostname>:<port>", username="mongodbuser@EXAMPLE.COM", authMechanism="GSSAPI", authMechanismProperties="SERVICE_NAME:<authentication service name>")
PLAIN SASL
The PLAIN Simple Authentication and Security Layer (SASL), as defined by RFC 4616, is a username-password authentication mechanism often used with TLS or another encryption layer.
Important
PLAIN SASL is a clear-text authentication mechanism. We strongly recommend that you use TLS/SSL with certificate validation when using PLAIN SASL to authenticate to MongoDB.
To learn more about how to enable TLS for your connection, see Configure Transport Layer Security (TLS).
To authenticate with SASL, set the authMechanism
connection option to PLAIN
.
You can set this option in two ways: by passing an argument to the
MongoClient
constructor or through a parameter in your connection string.
client = pymongo.MongoClient("mongodb://<hostname>:<port>", username="<username>", password="<password>", authMechanism="PLAIN", tls=True)
MONGODB-OIDC
Important
The MONGODB-OIDC authentication mechanism requires MongoDB v7.0 or later running on a Linux platform.
PyMongo supports OIDC authentication for workload identities. A workload identity is an identity you assign to a software workload, such as an application, service, script, or container, to authenticate and access other services and resources.
The following sections describe how to use the MONGODB-OIDC authentication mechanism to authenticate to various platforms.
For more information about the MONGODB-OIDC authentication mechanism, see OpenID Connect Authentication in the MongoDB Server manual.
Azure IMDS
If your application runs on an Azure VM, or otherwise uses the Azure Instance Metadata Service (IMDS), you can authenticate to MongoDB by using PyMongo's built-in Azure support.
You can configure OIDC for Azure IMDS in two ways: by passing arguments to the
MongoClient
constructor or through parameters in your connection string.
First, create a Python dictionary for your authentication mechanism properties, as shown
in the following example. Replace the <audience>
placeholder with
the percent-encoded audience configured on your MongoDB deployment.
properties = {"ENVIRONMENT": "azure", "TOKEN_RESOURCE": "<audience>"}
Then, set the following connection options:
username
: If you're using an Azure managed identity, set this to the client ID of the managed identity. If you're using a service principal to represent an enterprise application, set this to the application ID of the service principal.authMechanism
: Set to"MONGODB-OIDC"
.authMechanismProperties
: Set to theproperties
dictionary that you created in the previous step.
The following code example shows how to set these options when creating a
MongoClient
:
from pymongo import MongoClient # define properties and MongoClient properties = {"ENVIRONMENT": "azure", "TOKEN_RESOURCE": "<audience>"} client = MongoClient( "mongodb://<hostname>:<port>", username="<Azure client ID or application ID>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties )
Tip
If your application is running on an Azure VM, and only one managed identity is
associated with the VM, you can omit the username
connection option.
GCP IMDS
If your application runs on a GCP VM, or otherwise uses the GCP Instance Metadata Service, you can authenticate to MongoDB by using PyMongo's built-in GCP support.
You can configure OIDC for GCP IMDS in two ways: by passing arguments to the
MongoClient
constructor or through parameters in your connection string.
First, create a Python dictionary for your authentication mechanism properties, as shown
in the following example. Replace the <audience>
placeholder with
the percent-encoded audience configured on your MongoDB deployment.
properties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": "<audience>"}
Then, set the following connection options:
username
: The client ID of the GCP managed identity.authMechanism
: Set to"MONGODB-OIDC"
.authMechanismProperties
: Set to theproperties
dictionary that you created in the previous step.
The following code example shows how to set these options when creating a
MongoClient
:
from pymongo import MongoClient # define properties and MongoClient properties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": "<audience>"} client = MongoClient( "mongodb://<hostname>:<port>", username="<GCP identity client ID>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties )
Other Azure Environments
If your application runs on Azure Functions, App Service Environment (ASE), or Azure Kubernetes Service (AKS), you can use the azure-identity package to fetch authentication credentials.
First, use pip to install the azure-identity
library, as shown in the
following example:
python3 -m pip install azure-identity
Next, define a class that inherits from the OIDCCallback
class. This class must
implement a fetch()
method, which returns the OIDC token in the form of an
OIDCCallbackResult
object.
The following example shows how to define a callback class named MyCallback
. This class
includes a fetch()
method that retrieves an OIDC token from a file in the standard
service-account token-file location.
audience = "<audience configured on the MongoDB deployment>" client_id = "<Azure client ID>" class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: credential = DefaultAzureCredential(managed_identity_client_id=client_id) token = credential.get_token(f"{audience}/.default").token return OIDCCallbackResult(access_token=token)
After you define your callback class, create a Python dictionary that contains one key,
"OIDC_CALLBACK"
, whose value is an instance of your custom callback class:
properties = {"OIDC_CALLBACK": MyCallback()}
Finally, set the following connection options by passing arguments to the MongoClient
constructor:
authMechanism
: Set to"MONGODB-OIDC"
.authMechanismProperties
: Set to theproperties
dictionary that you created in the previous step.
from pymongo import MongoClient from azure.identity import DefaultAzureCredential from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult # define callback, properties, and MongoClient audience = "<audience configured on the MongoDB deployment>" client_id = "<Azure client ID>" class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: credential = DefaultAzureCredential(managed_identity_client_id=client_id) token = credential.get_token(f"{audience}/.default").token return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = MongoClient( "mongodb://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties )
GCP GKE
If your application runs on a GCP Google Kubernetes Engine (GKE) cluster with a configured service account, you can read the OIDC token from the standard service-account token-file location.
First, define a class that inherits from the OIDCCallback
class. This class must
implement a fetch()
method, which returns the OIDC token in the form of an
OIDCCallbackResult
object.
The following example shows how to define a callback class named MyCallback
. This class
includes a fetch()
method that retrieves an OIDC token from a file in the standard
service-account token-file location.
class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: with open("/var/run/secrets/kubernetes.io/serviceaccount/token") as fid: token = fid.read() return OIDCCallbackResult(access_token=token)
After you define your callback class, create a Python dictionary that contains one key,
"OIDC_CALLBACK"
, whose value is an instance of your custom callback class:
properties = {"OIDC_CALLBACK": MyCallback()}
Finally, set the following connection options by passing arguments to the MongoClient
constructor:
authMechanism
: Set to"MONGODB-OIDC"
.authMechanismProperties
: Set to theproperties
dictionary that you created in the previous step.
from pymongo import MongoClient from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult # define callback, properties, and MongoClient class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: with open("/var/run/secrets/kubernetes.io/serviceaccount/token") as fid: token = fid.read() return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = MongoClient( "mongodb://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties )
API Documentation
To learn more about using enterprise authentication mechanisms with PyMongo, see the following API documentation: