The OpenID Connect (OIDC) authentication mechanism allows you to authenticate to MongoDB by using a third-party identity provider, such as Azure or Google Cloud Platform (GCP).
You can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise Advanced, and only when authenticating to MongoDB v7.0 or later.
The code examples on this page use the following placeholders:
+srv
: Include this option in your connection string prefix only if you are connecting to a MongoDB Atlas cluster. To learn more about the +srv
option, see Connection String Formats in the MongoDB Server manual.
<Azure ID>
: The client ID or application ID of the Azure managed identity or enterprise application, if authenticating against Azure IMDS.
<hostname>
: The network address of your MongoDB deployment.
<port>
: The port number of your MongoDB deployment. If you omit this parameter, the driver uses the default port number (27017
). You don't need to specify a port when connecting to a MongoDB Atlas cluster.
<audience>
: The value of the audience
parameter configured on your MongoDB deployment.
To use the code examples on this page, replace these placeholders with your own values.
Important Percent-EncodingYou must percent-encode a username and password before you include them in a MongoDB URI. The quote_plus()
method, available in the urllib.parse module, is one way to perform this task. For example, calling quote_plus("and / or")
returns the string and+%2F+or
.
Don't percent-encode the username or password when passing them as arguments to MongoClient
.
The following sections describe how to use the MONGODB-OIDC authentication mechanism to authenticate to various platforms.
NoteBecause Python's Standard Library doesn't support asynchronous HTTP requests, all OIDC requests from PyMongo are synchronous and block the asyncio
loop.
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.
If your authMechanismProperties
values include a comma, you must use the MongoClient
constructor to set your authentication options.
First, create a Python dictionary for your authentication mechanism properties, as shown in the following example:
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 the properties
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 MongoClientproperties = {"ENVIRONMENT": "azure", "TOKEN_RESOURCE": "<audience>"}client = MongoClient( "mongodb[+srv]://<hostname>:<port>", username="<Azure ID>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
Include the following connection options in your connection string:
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 ENVIRONMENT:azure,TOKEN_RESOURCE:<audience>
.
The following code example shows how to set these options in your connection string:
from pymongo import MongoClienturi = ("mongodb[+srv]://<hostname>:<port>/?" "username=<username>" "&authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:<percent-encoded audience>")client = MongoClient(uri)
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.
If your application runs on a Google Compute Engine 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.
If your authMechanismProperties
values include a comma, you must use the MongoClient
constructor to set your authentication options.
First, create a Python dictionary for your authentication mechanism properties, as shown in the following example.
properties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": "<audience>"}
Then, set the following connection options:
authMechanism
: Set to "MONGODB-OIDC"
.
authMechanismProperties
: Set to the properties
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 MongoClientproperties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": "<audience>"}client = MongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
Include the following connection options in your connection string:
authMechanism
: Set to MONGODB-OIDC
.
authMechanismProperties
: Set to ENVIRONMENT:gcp,TOKEN_RESOURCE:<audience>
.
The following code example shows how to set these options in your connection string:
from pymongo import MongoClienturi = ("mongodb[+srv]://<hostname>:<port>/?" "&authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:<percent-encoded audience>")client = MongoClient(uri)
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>"client_id = "<Azure 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 the followingarguments to the MongoClient
constructor:
authMechanism
: Set to "MONGODB-OIDC"
.
authMechanismProperties
: Set to the properties
dictionary that you created in the previous step.
Select the Synchronous or Asynchronous tab to see the corresponding code:
client = MongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
client = AsyncMongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
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 the following arguments to the MongoClient
constructor:
authMechanism
: Set to "MONGODB-OIDC"
.
authMechanismProperties
: Set to the properties
dictionary that you created in the previous step.
Select the Synchronous or Asynchronous tab to see the corresponding code:
client = MongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
client = AsyncMongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
If your application runs on a Kubernetes cluster, you can authenticate to MongoDB by using PyMongo's built-in Kubernetes support.
You can configure OIDC for Kubernetes in two ways: by passing arguments to the MongoClient
constructor or through parameters in your connection string. Select from the following tabs to see how to enable Kubernetes authentication for your application:
properties = {"ENVIRONMENT": "k8s"}client = MongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
uri = ("mongodb[+srv]://<hostname>:<port>/?" "authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:k8s")client = MongoClient(uri)
properties = {"ENVIRONMENT": "k8s"}client = AsyncMongoClient( "mongodb[+srv]://<hostname>:<port>", authMechanism="MONGODB-OIDC", authMechanismProperties=properties)
uri = ("mongodb[+srv]://<hostname>:<port>/?" "authMechanism=MONGODB-OIDC" "&authMechanismProperties=ENVIRONMENT:k8s")client = AsyncMongoClient(uri)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4