Docs Menu
Docs Home
/ / /
PyMongo
/

Enterprise Authentication Mechanisms

On this page

  • Overview
  • Kerberos
  • PLAIN SASL
  • MONGODB-OIDC
  • Azure IMDS
  • GCP IMDS
  • Other Azure Environments
  • GCP GKE
  • API Documentation

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.

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 uses mongodb 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.

Note

If your authMechanismProperties values include a comma, you must use the MongoClient constructor to set your authentication options.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="mongodbuser@EXAMPLE.COM",
authMechanism="GSSAPI",
authMechanismProperties="SERVICE_NAME:<authentication service name>")
uri = ("mongodb://mongodbuser%40EXAMPLE.COM@<hostname>:<port>/?"
"&authMechanism=GSSAPI"
"&authMechanismProperties=SERVICE_NAME:<authentication service name>")
client = pymongo.MongoClient(uri)

First, install the winkerberos module. Then, 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".

  • password: Optional. If the user to authenticate is different from the user that owns the application process, set this option to the authenticating user's password.

  • authMechanismProperties: Optional. This option includes multiple authentication properties. To specify more than one of the following properties, use a comma-delimited list.

    • SERVICE_NAME: By default, MongoDB uses mongodb as the authentication service name. Use this option to specify a different service name.

    • CANONICALIZE_HOST_NAME: Whether to use the fully qualified domain name (FQDN) of the MongoDB host for the server principal.

    • SERVICE_REALM: The service realm. Use this option when the user's realm is different from the service's realm.

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",
password="<user password>",
authMechanismProperties="SERVICE_NAME:<authentication service name>,
CANONICALIZE_HOST_NAME:true,
SERVICE_REALM:<service realm>")
uri = ("mongodb://mongodbuser%40EXAMPLE.COM:<percent-encoded user password>"
"@<hostname>:<port>/?"
"&authMechanism=GSSAPI"
"&authMechanismProperties="
"SERVICE_NAME:<authentication service name>,"
"CANONICALIZE_HOST_NAME:true,"
"SERVICE_REALM:<service realm>")
client = pymongo.MongoClient(uri)

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.

Note

If your authMechanismProperties values include a comma, you must use the MongoClient constructor to set your authentication options.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="<db_username>",
password="<db_password>",
authMechanism="PLAIN",
tls=True)
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?"
"&authMechanism=PLAIN"
"&tls=true")
client = pymongo.MongoClient(uri)

Important

The MONGODB-OIDC authentication mechanism requires MongoDB Server 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 and MongoDB Server Parameters in the MongoDB Server manual.

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. Replace the <audience> placeholder with the value of the audience parameter configured on your MongoDB deployment.

The following code example shows how to set these options in your connection string:

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://<hostname>:<port>",
username="<Azure client ID or application 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>. Replace the <audience> placeholder with the value of the audience parameter configured on your MongoDB deployment.

    The following code example shows how to set these options in your connection string:

from pymongo import MongoClient
# define URI and MongoClient
uri = ("mongodb://<hostname>:<port>/?"
"username=<Azure client ID or application ID>"
"&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. Replace the <audience> placeholder with the value of the audience parameter configured on your MongoDB deployment.

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://<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>. Replace the <audience> placeholder with the value of the audience parameter configured on your MongoDB deployment.

The following code example shows how to set these options in your connection string:

from pymongo import MongoClient
# define URI and MongoClient
uri = ("mongodb://<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 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 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 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
)

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://<hostname>:<port>",
authMechanism="MONGODB-OIDC",
authMechanismProperties=properties
)

To learn more about using enterprise authentication mechanisms with PyMongo, see the following API documentation:

Back

Authentication Mechanisms