Authentication Mechanisms
On this page
Overview
This guide describes the mechanisms you can use in PyMongo to authenticate users.
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
.
SCRAM-SHA-256
SCRAM-SHA-256, as defined by RFC 7677, is the default authentication mechanism on MongoDB deployments running MongoDB v4.0 or later.
To authenticate with this mechanism, set the following connection options:
db_username
: The username to authenticate. Percent-encode this value before including it in a connection URI.db_password
: The password to authenticate. Percent-encode this value before including it in a connection URI.authSource
: The MongoDB database to authenticate against. By default, PyMongo authenticates against the database in the connection URI, if you include one. If you don't, it authenticates against theadmin
database.authMechanism
: Set toSCRAM-SHA-256
.
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="<db_username>", password="<db_password>", authSource="<authentication database>", authMechanism="SCRAM-SHA-256")
uri = ("mongodb://<percent-encoded db_username>:<percent-encoded db_password>" "@<hostname>:<port>/?" "authSource=<authentication database>" "&authMechanism=SCRAM-SHA-256") client = pymongo.MongoClient(uri)
SCRAM-SHA-1
SCRAM-SHA-1, as defined by RFC 5802, is the default authentication mechanism on MongoDB deployments running MongoDB v3.6.
To authenticate with this mechanism, set the following connection options:
db_username
: The username to authenticate. Percent-encode this value before including it in a connection URI.db_password
: The password to authenticate. Percent-encode this value before including it in a connection URI.authSource
: The MongoDB database to authenticate against. By default, PyMongo authenticates against theadmin
database.authMechanism
: Set to"SCRAM-SHA-1"
.
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="<db_username>", password="<db_password>", authSource="<authentication database>", authMechanism="SCRAM-SHA-1")
uri = ("mongodb://<percent-encoded db_username>:<percent-encoded db_password>" "@<hostname>:<port>/?" "authSource=<authentication database>" "&authMechanism=SCRAM-SHA-1") client = pymongo.MongoClient(uri)
MONGODB-X509
If you enable TLS, during the TLS handshake, PyMongo can present an X.509 client certificate to MongoDB to prove its identity. The MONGODB-X509 authentication mechanism uses this certificate to authenticate the client.
To authenticate with this mechanism, set the following connection options:
tls
: Set toTrue
.tlsCertificateKeyFile
: The file path of the.pem
file that contains your client certificate and private key.authMechanism
: Set to"MONGODB-X509"
.
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>", 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)
MONGODB-AWS
Important
The MONGODB-AWS authentication mechanism requires MongoDB v4.4 or later.
The MONGODB-AWS authentication mechanism uses AWS IAM (Amazon Web Services Identity and
Access Management) or AWS Lambda credentials to authenticate your application.
To use MONGODB-AWS for authentication, you must install PyMongo with the
aws
option, as shown in the following example:
python -m pip install pymongo[aws]
PyMongo uses Boto3, the AWS SDK for Python, to handle credentials. Boto3 tries to retrieve AWS credentials from the following sources, in the order listed:
Named arguments passed to the
MongoClient
constructor or parameters in the connection URIEnvironment variables
Shared credentials file
AWS config file
AssumeRole
request to the AWS Security Token Service (STS)AssumeRoleWithWebIdentity
request to the AWS STSInstance metadata service on an Amazon EC2 instance with an IAM role configured
The following sections describe how to use PyMongo to retrieve credentials from these sources and use them to authenticate your application.
MongoClient
Credentials
First, PyMongo checks whether you passed AWS credentials
to the MongoClient
constructor, either as a named argument or as part of the
connection URI. To pass your credentials to MongoClient
,
set the following connection options:
username
: The AWS IAM access key ID to authenticate. Percent-encode this value before including it in a connection URI.password
: The AWS IAM secret access key. Percent-encode this value before including it in a connection URI.authMechanism
: Set to"MONGODB-AWS"
.
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="<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)
Environment Variables
If you don't provide a username and password when you construct your MongoClient
object, PyMongo tries to retrieve AWS credentials from the following
environment variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_SESSION_TOKEN
To use these environment variables to authenticate your application, first set them to the AWS IAM values needed for authentication, as shown in the following code example:
export AWS_ACCESS_KEY_ID=<AWS IAM access key ID> export AWS_SECRET_ACCESS_KEY=<AWS IAM secret access key> export AWS_SESSION_TOKEN=<AWS session token>
Important
Don't percent-encode the values in these environment variables.
After you set these environment variables, set the authMechanism
connection option to "MONGODB-AWS"
.
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>", authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS" client = pymongo.MongoClient(uri)
Tip
AWS Lambda
AWS Lambda runtimes can automatically set these environment variables during initialization. For more information about using environment variables in an AWS Lambda environment, see Using Lambda environment variables in the AWS documentation.
Shared Credentials File
If PyMongo doesn't find AWS credentials in the preceding environment variables, it tries to read them from a shared credentials file.
To use a shared credentials file to authenticate your application, ensure that the file exists in your environment and is configured correctly. To learn how to create a shared credentials file, see Credentials in the Boto3 documentation and Configuration in the AWS documentation.
After you create the shared credentials file, set the authMechanism
connection option to "MONGODB-AWS"
.
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>", authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS" client = pymongo.MongoClient(uri)
Tip
To prevent PyMongo from using a shared credentials file for authentication, perform one of the following actions:
Set the
AWS_SHARED_CREDENTIALS_FILE
environment variable to""
in your terminal.Add
os.environ["AWS_SHARED_CREDENTIALS_FILE"] = ""
to your script or application.Create an AWS profile specifically for your MongoDB credentials. Set the
AWS_PROFILE
environment variable to the name of the profile you created.
AWS Config File
If PyMongo doesn't find credentials in the shared credentials file, it tries to read them from an AWS config file.
To use an AWS config file to authenticate your application, ensure that the file exists in your environment and is configured correctly. To learn how to create an AWS config file, see Credentials in the Boto3 documentation and Configuration in the AWS documentation.
After you create the config file, set the authMechanism
connection option to "MONGODB-AWS"
.
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>", authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS" client = pymongo.MongoClient(uri)
AssumeRole Request
Instead of storing AWS credentials in your AWS config file, you can instruct
PyMongo to make an AssumeRole
request to an AWS STS endpoint. This request
returns temporary credentials that your application can use for authentication.
To authenticate with temporary AWS IAM credentials returned by an AssumeRole
request,
ensure that the AWS config file exists in your environment and is configured correctly.
To learn how to create and configure
an AWS config file, see
Credentials
in the Boto3 documentation and Configuration
in the AWS documentation.
After you create the config file, set the following connection options:
username
: The AWS IAM access key ID to authenticate returned by theAssumeRole
request. Percent-encode this value before including it in a connection URI.password
: The AWS IAM secret access key returned by theAssumeRole
request. Percent-encode this value before including it in a connection URI..authMechanismProperties
: Set toAWS_SESSION_TOKEN:
and the AWS session token returned by theAssumeRole
request.authMechanism
: Set to"MONGODB-AWS"
.
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="<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)
For more information about using the AssumeRole
request to authenticate your
application, see the following AWS documentation:
AssumeRoleWithWebIdentity
Important
Your application must use pymongo_auth_aws
v1.1.0 or later for EKS support.
If your application authenticates users for your EKS cluster from an OpenID Connect (OIDC)
identity provider, PyMongo can make an AssumeRoleWithWebIdentity
request
to exchange the OIDC token for temporary AWS credentials for your application.
To authenticate with temporary AWS IAM credentials returned by an
AssumeRoleWithWebIdentity
request, ensure that the AWS config file exists in your
environment and is configured correctly. To learn how to create and configure
an AWS config file, see
Credentials
in the Boto3 documentation and Configuration
in the AWS documentation.
After you configure your environment for an AssumeRoleWithWebIdentity
request,
set the authMechanism
connection option to "MONGODB-AWS"
.
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>", authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS" client = pymongo.MongoClient(uri)
For more information about using an AssumeRoleWithWebIdentity
request to
authenticate your application, see the following AWS documentation:
ECS Container or EC2 Instance
If your application runs in an Amazon Elastic Cloud Compute (EC2) instance in an Elastic Container Service (ECS) container, PyMongo can automatically retrieve temporary AWS credentials from an ECS endpoint.
To use temporary credentials from within an EC2 instance, set the authMechanism
connection option to "MONGODB-AWS"
.
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>", authMechanism="MONGODB-AWS")
uri = "mongodb://<hostname>:<port>/?&authMechanism=MONGODB-AWS" client = pymongo.MongoClient(uri)
API Documentation
To learn more about authenticating your application in PyMongo, see the following API documentation: