Docs Menu
Docs Home
/ / /
PyMongo

Secure Your Data

On this page

  • Overview
  • Sample Application
  • SCRAM-SHA-256
  • SCRAM-SHA-1
  • MONGODB-X509
  • MONGODB-AWS
  • MongoClient Credentials
  • Environment Variables
  • Shared Credentials File
  • AWS Config File
  • AssumeRole Request
  • AssumeRoleWithWebIdentity
  • ECS Container or EC2 Instance
  • Kerberos
  • Unix
  • Windows
  • PLAIN SASL
  • MONGODB-OIDC
  • Azure IMDS
  • GCP IMDS
  • Other Azure Environments
  • GCP GKE

MongoDB supports multiple mechanisms that you can use to authenticate your application. This page contains code examples that show each of these mechanisms.

Tip

To learn more about any of the authentication mechanisms on this page, see the Authentication Mechanisms and Enterprise Authentication Mechanisms pages.

To use an authentication example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <hostname>, with the relevant values for your MongoDB deployment.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have PyMongo installed.

  2. Copy the following code and paste it into a new .py file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

1from pymongo import MongoClient
2
3try:
4 # start example code here
5
6 # end example code here
7
8 client.admin.command("ping")
9 print("Connected successfully")
10
11 # other application code
12
13 client.close()
14
15except Exception as e:
16 raise Exception(
17 "The following error occurred: ", e)
client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="<db_username>",
password="<db_password>",
authSource="<authentication database>",
authMechanism="SCRAM-SHA-256")
uri = ("mongodb://<percent-encoded username>:<percent-encoded password>"
"@<hostname>:<port>/?"
"authSource=<authentication database>"
"&authMechanism=SCRAM-SHA-256")
client = pymongo.MongoClient(uri)

To learn more about SCRAM-SHA-256 authentication, see SCRAM-SHA-256 in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="<db_username>",
password="<db_password>",
authSource="<authentication database>",
authMechanism="SCRAM-SHA-1")
uri = ("mongodb://<percent-encoded username>:<percent-encoded password>"
"@<hostname>:<port>/?"
"authSource=<authentication database>"
"&authMechanism=SCRAM-SHA-1")
client = pymongo.MongoClient(uri)

To learn more about SCRAM-SHA-1 authentication, see SCRAM-SHA-1 in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
tls=True,
tlsCertificateKeyFile="/path/to/client.pem",
authMechanism="MONGODB-X509")
uri = ("mongodb://<hostname>:<port>/?"
"tls=true"
"&tlsCertificateKeyFile=path/to/client.pem"
"&authMechanism=MONGODB-X509")
client = pymongo.MongoClient(uri)

To learn more about MONGODB-X509 authentication, see MONGODB-X509 in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="<AWS IAM access key ID>",
password="<AWS IAM secret access key>",
authMechanism="MONGODB-AWS")
uri = ("mongodb://<percent-encoded AWS IAM access key ID>:"
"<percent-encoded AWS IAM secret access key>"
"@<hostname>:<port>/?"
"&authMechanism=MONGODB-AWS")
client = pymongo.MongoClient(uri)

To learn more about authenticating with AWS MongoClient credentials, see MongoClient Credentials in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS"
client = pymongo.MongoClient(uri)

To learn more about authenticating with AWS environment variables, see Environment Variables in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS"
client = pymongo.MongoClient(uri)

To learn more about authenticating with a shared AWS credentials file, see Shared Credentials File in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS"
client = pymongo.MongoClient(uri)

To learn more about authenticating with an AWS config file, see AWS Config File in the Authentication guide.

client = pymongo.MongoClient("mongodb://@<hostname>:<port>",
username="<AWS IAM access key ID>",
password="<AWS IAM secret access key>",
authMechanismProperties="AWS_SESSION_TOKEN:<AWS session token>",
authMechanism="MONGODB-AWS")
uri = ("mongodb://<percent-encoded AWS IAM access key ID>:"
"<percent-encoded AWS IAM secret access key>"
"@<hostname>:<port>/?"
"authMechanismProperties=AWS_SESSION_TOKEN:<AWS session token>"
"&authMechanism=MONGODB-AWS")
client = pymongo.MongoClient(uri)

To learn more about authenticating with an AssumeRole request, see AssumeRole Request in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS"
client = pymongo.MongoClient(uri)

To learn more about authenticating with an AssumeRoleWithWebIdentity request, see AssumeRoleWithWebIdentity in the Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS"
client = pymongo.MongoClient(uri)

To learn more about authenticating from an ECS container, see ECS Container or EC2 Instance in the Authentication guide.

Note

MongoDB Enterprise Only

Kerberos authentication is available only in MongoDB Enterprise.

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)

To learn more about authenticating with Kerberos, see Kerberos in the Enterprise Authentication guide.

client = pymongo.MongoClient("mongodb://<hostname>:<port>",
username="<db_username>",
authMechanism="GSSAPI",
password="<db_password>",
authMechanismProperties="SERVICE_NAME:<authentication service name>,
CANONICALIZE_HOST_NAME:true,
SERVICE_REALM:<service realm>")
uri = ("mongodb://<percent-encoded username>:<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)

To learn more about authenticating with Kerberos, see Kerberos in the Enterprise Authentication guide.

Note

MongoDB Enterprise Only

PLAIN SASL authentication is available only in MongoDB Enterprise.

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)

To learn more about authenticating with PLAIN SASL, see PLAIN SASL in the Enterprise Authentication guide.

Note

MongoDB Enterprise Only

MONGODB-OIDC authentication is available only in MongoDB Enterprise.

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

To learn more about authenticating with OIDC, see Azure IMDS in the Authentication guide.

from pymongo import MongoClient
# define properties and MongoClient
properties = {"ENVIRONMENT": "gcp", "TOKEN_RESOURCE": "<audience>"}
client = MongoClient(
"mongodb://<hostname>:<port>",
authMechanism="MONGODB-OIDC",
authMechanismProperties=properties
)
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)

To learn more about authenticating with OIDC, see GCP IMDS in the Authentication guide.

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
)

To learn more about authenticating with OIDC, see Other Azure Environments in the Authentication guide.

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 authenticating with OIDC, see GCP GKE in the Authentication guide.

Back

Multi-Field Join