Docs Menu
Docs Home
/ / /
PyMongo
/ /

OIDC (Workload Identity Federation)

On this page

  • Overview
  • Code Placeholders
  • Using OIDC Authentication in Your Application
  • Azure IMDS
  • GCP IMDS
  • Other Azure Environments
  • GCP GKE

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.

Tip

OIDC Authentication

To learn more about configuring MongoDB Atlas for OIDC authentication, see Set up Workforce Identity Federation with OIDC in the Atlas documentation.

For more information about using OIDC authentication with MongoDB, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.

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-Encoding

You 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.

Note

Because 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.

Note

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 MongoClient
# define properties and MongoClient
properties = {"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 MongoClient
# define URI and MongoClient
uri = ("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.

Note

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 MongoClient
# define properties and MongoClient
properties = {"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 MongoClient
# define URI and MongoClient
uri = ("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 arguments to the MongoClient constructor:

  • authMechanism: Set to "MONGODB-OIDC".

  • authMechanismProperties: Set to the properties 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>"
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)
properties = {"OIDC_CALLBACK": MyCallback()}
client = MongoClient(
"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 arguments to the MongoClient constructor:

  • authMechanism: Set to "MONGODB-OIDC".

  • authMechanismProperties: Set to the properties 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[+srv]://<hostname>:<port>",
authMechanism="MONGODB-OIDC",
authMechanismProperties=properties
)

Back

AWS IAM