Authentication Examples

    Username and password must be percent-escaped with in Python 3, or urllib.quote_plus() in Python 2, to be used in a MongoDB URI. For example, in Python 3:

    SCRAM-SHA-256 (RFC 7677)

    New in version 3.7.

    SCRAM-SHA-256 is the default authentication mechanism supported by a cluster configured for authentication with MongoDB 4.0 or later. Authentication requires a username, a password, and a database name. The default database name is “admin”, this can be overridden with the authSource option. Credentials can be specified as arguments to :

    1. >>> from pymongo import MongoClient
    2. >>> client = MongoClient('example.com',
    3. ... username='user',
    4. ... password='password',
    5. ... authSource='the_database',
    6. ... authMechanism='SCRAM-SHA-256')

    Or through the MongoDB URI:

    1. >>> uri = "mongodb://user:password@example.com/?authSource=the_database&authMechanism=SCRAM-SHA-256"
    2. >>> client = MongoClient(uri)

    SCRAM-SHA-1 (RFC 5802)

    New in version 2.8.

    SCRAM-SHA-1 is the default authentication mechanism supported by a cluster configured for authentication with MongoDB 3.0 or later. Authentication requires a username, a password, and a database name. The default database name is “admin”, this can be overridden with the authSource option. Credentials can be specified as arguments to :

    1. >>> from pymongo import MongoClient
    2. >>> client = MongoClient('example.com',
    3. ... username='user',
    4. ... password='password',
    5. ... authSource='the_database',
    6. ... authMechanism='SCRAM-SHA-1')

    Or through the MongoDB URI:

    1. >>> uri = "mongodb://user:password@example.com/?authSource=the_database&authMechanism=SCRAM-SHA-1"
    2. >>> client = MongoClient(uri)

    For best performance on Python versions older than 2.7.8 install backports.pbkdf2.

    Warning

    MONGODB-CR was deprecated with the release of MongoDB 3.6 and is no longer supported by MongoDB 4.0.

    Before MongoDB 3.0 the default authentication mechanism was MONGODB-CR, the “MongoDB Challenge-Response” protocol:

    1. >>> from pymongo import MongoClient
    2. ... username='user',
    3. ... password='password',
    4. ... authMechanism='MONGODB-CR')
    5. >>>
    6. >>> uri = "mongodb://user:password@example.com/?authSource=the_database&authMechanism=MONGODB-CR"
    7. >>> client = MongoClient(uri)

    Default Authentication Mechanism

    If no mechanism is specified, PyMongo automatically uses MONGODB-CR when connected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 when connected to MongoDB 3.0 through 3.6, and negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB 4.0+.

    Default Database and “authSource”

    You can specify both a default database and the authentication database in the URI:

    1. >>> uri = "mongodb://user:password@example.com/default_db?authSource=admin"
    2. >>> client = MongoClient(uri)

    PyMongo will authenticate on the “admin” database, but the default database will be “default_db”:

    1. >>> # get_database with no "name" argument chooses the DB from the URI
    2. >>> print(db.name)
    3. 'default_db'

    New in version 2.6.

    The MONGODB-X509 mechanism authenticates a username derived from the distinguished subject name of the X.509 certificate presented by the driver during TLS/SSL negotiation. This authentication method requires the use of TLS/SSL connections with certificate validation and is available in MongoDB 2.6 and newer:

    1. >>> uri = "mongodb://<X.509 derived username>@example.com/?authMechanism=MONGODB-X509"
    2. >>> client = MongoClient(uri,
    3. ... tls=True,
    4. ... tlsCertificateKeyFile='/path/to/client.pem',
    5. ... tlsCAFile='/path/to/ca.pem')
    6. >>>

    Changed in version 3.4: When connected to MongoDB >= 3.4 the username is no longer required.

    GSSAPI (Kerberos)

    New in version 2.5.

    GSSAPI (Kerberos) authentication is available in the Enterprise Edition of MongoDB.

    To authenticate using GSSAPI you must first install the python kerberos or module using easy_install or pip. Make sure you run kinit before using the following authentication methods:

    1. $ kinit mongodbuser@EXAMPLE.COM
    2. mongodbuser@EXAMPLE.COM's Password:
    3. $ klist
    4. Credentials cache: FILE:/tmp/krb5cc_1000
    5. Principal: mongodbuser@EXAMPLE.COM
    6. Issued Expires Principal
    7. Feb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/EXAMPLE.COM@EXAMPLE.COM

    Now authenticate using the MongoDB URI. GSSAPI authenticates against the $external virtual database so you do not have to specify a database in the URI:

    1. >>> # Note: the kerberos principal must be url encoded.
    2. >>> from pymongo import MongoClient
    3. >>> uri = "mongodb://mongodbuser%40EXAMPLE.COM@mongo-server.example.com/?authMechanism=GSSAPI"
    4. >>> client = MongoClient(uri)
    5. >>>

    The default service name used by MongoDB and PyMongo is mongodb. You can specify a custom service name with the authMechanismProperties option:

    1. >>> from pymongo import MongoClient
    2. >>> uri = "mongodb://mongodbuser%40EXAMPLE.COM@mongo-server.example.com/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myservicename"
    3. >>> client = MongoClient(uri)

    Windows (SSPI)

    New in version 3.3.

    First install the module. Unlike authentication on Unix kinit is not used. If the user to authenticate is different from the user that owns the application process provide a password to authenticate:

      Two extra authMechanismProperties are supported on Windows platforms:

      • CANONICALIZE_HOST_NAME - Uses the fully qualified domain name (FQDN) of the MongoDB host for the server principal (GSSAPI libraries on Unix do this by default):

        1. >>> uri = "mongodb://mongodbuser%40EXAMPLE.COM@example.com/?authMechanism=GSSAPI&authMechanismProperties=CANONICALIZE_HOST_NAME:true"
      • SERVICE_REALM - This is used when the user’s realm is different from the service’s realm:

        1. >>> uri = "mongodb://mongodbuser%40EXAMPLE.COM@example.com/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_REALM:otherrealm"

      SASL PLAIN (RFC 4616)

      New in version 2.6.

      MongoDB Enterprise Edition version 2.6 and newer support the SASL PLAIN authentication mechanism, initially intended for delegating authentication to an LDAP server. Using the PLAIN mechanism is very similar to MONGODB-CR. These examples use the $external virtual database for LDAP support:

      SASL PLAIN is a clear-text authentication mechanism. We strongly recommend that you connect to MongoDB using TLS/SSL with certificate validation when using the SASL PLAIN mechanism:

      1. >>> from pymongo import MongoClient
      2. >>> client = MongoClient(uri,
      3. ... tls=True,
      4. ... tlsCertificateKeyFile='/path/to/client.pem',
      5. ... tlsCAFile='/path/to/ca.pem')
      6. >>>

      New in version 3.11.

      The MONGODB-AWS authentication mechanism is available in MongoDB 4.4+ and requires extra pymongo dependencies. To use it, install pymongo with the aws extra:

      1. $ python -m pip install 'pymongo[aws]'

      Credentials can be configured through the MongoDB URI, environment variables, or the local EC2 or ECS endpoint. The order in which the client searches for credentials is:

      1. Credentials passed through the URI
      2. Environment variables
      3. ECS endpoint if and only if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
      4. EC2 endpoint

      MONGODB-AWS authenticates against the “$external” virtual database, so none of the URIs in this section need to include the authSource URI option.

      Applications can authenticate using AWS IAM credentials by providing a valid access key id and secret access key pair as the username and password, respectively, in the MongoDB URI. A sample URI would be:

      1. >>> from pymongo import MongoClient
      2. >>> uri = "mongodb://<access_key_id>:<secret_access_key>@localhost/?authMechanism=MONGODB-AWS"
      3. >>> client = MongoClient(uri)

      Note

      The access_key_id and secret_access_key passed into the URI MUST be .

      AssumeRole

      Applications can authenticate using temporary credentials returned from an assume role request. These temporary credentials consist of an access key ID, a secret access key, and a security token passed into the URI. A sample URI would be:

      1. >>> from pymongo import MongoClient
      2. >>> uri = "mongodb://<access_key_id>:<secret_access_key>@example.com/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<session_token>"
      3. >>> client = MongoClient(uri)

      Note

      The access_key_id, secret_access_key, and session_token passed into the URI MUST be .

      When the username and password are not provided and the MONGODB-AWS mechanism is set, the client will fallback to using the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN for the access key ID, secret access key, and session token, respectively:

      1. $ export AWS_ACCESS_KEY_ID=<access_key_id>
      2. $ export AWS_SECRET_ACCESS_KEY=<secret_access_key>
      3. $ export AWS_SESSION_TOKEN=<session_token>
      4. $ python
      5. >>> from pymongo import MongoClient
      6. >>> uri = "mongodb://example.com/?authMechanism=MONGODB-AWS"
      7. >>> client = MongoClient(uri)

      Note

      No username, password, or session token is passed into the URI. PyMongo will use credentials set via the environment variables. These environment variables MUST NOT be .

      ECS Container

      Applications can authenticate from an ECS container via temporary credentials assigned to the machine. A sample URI on an ECS container would be:

      1. >>> from pymongo import MongoClient
      2. >>> uri = "mongodb://localhost/?authMechanism=MONGODB-AWS"
      3. >>> client = MongoClient(uri)

      Note

      No username, password, or session token is passed into the URI. PyMongo will query the ECS container endpoint to obtain these credentials.

      Applications can authenticate from an EC2 instance via temporary credentials assigned to the machine. A sample URI on an EC2 machine would be:

      1. >>> from pymongo import MongoClient
      2. >>> uri = "mongodb://localhost/?authMechanism=MONGODB-AWS"

      Note