Authentication Examples

MongoDB supports several different authentication mechanisms. These examplescover all authentication methods currently supported by PyMongo, documentingPython module and MongoDB version dependencies.

Percent-Escaping Username and Password

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

  1. >>> from pymongo import MongoClient
  2. >>> import urllib.parse
  3. >>> username = urllib.parse.quote_plus('user')
  4. >>> username
  5. 'user'
  6. >>> password = urllib.parse.quote_plus('pass/word')
  7. >>> password
  8. 'pass%2Fword'
  9. >>> MongoClient('mongodb://%s:%s@127.0.0.1' % (username, password))
  10. ...

SCRAM-SHA-256 (RFC 7677)

New in version 3.7.

SCRAM-SHA-256 is the default authentication mechanism supported by a clusterconfigured for authentication with MongoDB 4.0 or later. Authenticationrequires a username, a password, and a database name. The default databasename is “admin”, this can be overidden with the authSource option.Credentials can be specified as arguments toMongoClient:

  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 clusterconfigured for authentication with MongoDB 3.0 or later. Authenticationrequires a username, a password, and a database name. The default databasename is “admin”, this can be overidden with the authSource option.Credentials can be specified as arguments toMongoClient:

  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.

MONGODB-CR

Warning

MONGODB-CR was deprecated with the release of MongoDB 3.6 andis 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. >>> client = MongoClient('example.com',
  3. ... username='user',
  4. ... password='password',
  5. ... authMechanism='MONGODB-CR')
  6. >>>
  7. >>> uri = "mongodb://user:password@example.com/?authSource=the_database&authMechanism=MONGODB-CR"
  8. >>> client = MongoClient(uri)

Default Authentication Mechanism

If no mechanism is specified, PyMongo automatically uses MONGODB-CR whenconnected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 when connected toMongoDB 3.0 through 3.6, and negotiates the mechanism to use (SCRAM-SHA-1or 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 theURI:

  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 databasewill be “default_db”:

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

MONGODB-X509

New in version 2.6.

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

  1. >>> import ssl
  2. >>> from pymongo import MongoClient
  3. >>> client = MongoClient('example.com',
  4. ... username="<X.509 derived username>"
  5. ... authMechanism="MONGODB-X509",
  6. ... ssl=True,
  7. ... ssl_certfile='/path/to/client.pem',
  8. ... ssl_cert_reqs=ssl.CERT_REQUIRED,
  9. ... ssl_ca_certs='/path/to/ca.pem')

MONGODB-X509 authenticates against the $external virtual database, so youdo not have to specify a database in the URI:

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

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

Unix

To authenticate using GSSAPI you must first install the python kerberos orpykerberos module using easy_install or pip. Make sure you run kinit beforeusing 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.  
  7. Issued Expires Principal
  8. 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 theURI:

  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 canspecify 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 winkerberos module. Unlike authentication on Unix kinit isnot used. If the user to authenticate is different from the user that owns theapplication process provide a password to authenticate:

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

Two extra authMechanismProperties are supported on Windows platforms:

  • CANONICALIZE_HOST_NAME - Uses the fully qualified domain name (FQDN) of theMongoDB host for the server principal (GSSAPI libraries on Unix do this bydefault):
  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 PLAINauthentication mechanism, initially intended for delegating authenticationto an LDAP server. Using the PLAIN mechanism is very similar to MONGODB-CR.These examples use the $external virtual database for LDAP support:

  1. >>> from pymongo import MongoClient
  2. >>> uri = "mongodb://user:password@example.com/?authMechanism=PLAIN"
  3. >>> client = MongoClient(uri)
  4. >>>

SASL PLAIN is a clear-text authentication mechanism. We strongly recommendthat you connect to MongoDB using SSL with certificate validation when usingthe SASL PLAIN mechanism:

  1. >>> import ssl
  2. >>> from pymongo import MongoClient
  3. >>> uri = "mongodb://user:password@example.com/?authMechanism=PLAIN"
  4. >>> client = MongoClient(uri,
  5. ... ssl=True,
  6. ... ssl_certfile='/path/to/client.pem',
  7. ... ssl_cert_reqs=ssl.CERT_REQUIRED,
  8. ... ssl_ca_certs='/path/to/ca.pem')
  9. >>>