Docs Menu
Docs Home
/ / /
PyMongo
/ /

LDAP (PLAIN SASL)

On this page

  • Overview
  • Code Placeholders
  • Using PLAIN Authentication in Your Application
  • API Documentation

The PLAIN authentication mechanism allows you to use your Lightweight Directory Access Protocol (LDAP) username and password to authenticate to MongoDB. LDAP authentication uses the PLAIN Simple Authentication and Security Layer (SASL) defined in RFC-4616.

You can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise Advanced.

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

The code examples on this page use the following placeholders:

  • +srv: Include this option in your connection string prefix only if you are connecting to a MongoDB Atlas cluster. To learn more about the +srv option, see Connection String Formats in the MongoDB Server manual.

  • <username>: Your LDAP username.

  • <password>: Your LDAP password.

  • <hostname>: The network address of your MongoDB deployment.

  • <port>: The port number of your MongoDB deployment. If you omit this parameter, the driver uses the default port number (27017). You don't need to specify a port when connecting to a MongoDB Atlas cluster.

  • <authenticationDb>: The MongoDB database that contains the user's LDAP credentials. If you omit this parameter, the driver uses the default database (admin).

To use the code examples on this page, replace these placeholders with your own values.

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.

To use PLAIN to authenticate, 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[+srv]://<hostname>:<port>",
username="<username>",
password="<password>",
authSource="<authenticationDb>",
authMechanism="PLAIN",
tls=True)
uri = ("mongodb[+srv]://<username>:<password>@<hostname>:<port>/?"
"authSource=<authenticationDb>"
"&authMechanism=PLAIN"
"&tls=true")
client = pymongo.MongoClient(uri)

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

Back

OIDC