scram

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: scram-sha-256, scram-sha-256-tls, scram-sha-1, scram-sha-1-tls -->

SCRAM Authentication

Overview

Salted Challenge Response Authentication Mechanism (SCRAM) is a family of authentication mechanisms that use a challenge-response mechanism to authenticate the user. SCRAM-SHA-256, as defined by RFC 7677 , uses the SHA-256 algorithm to hash your password, is the default authentication mechanism for deployments running MongoDB v.4.0 or later. SCRAM-SHA-1, as defined by RFC 5802, is supported for compatibility with deployments running MongoDB v3.6.

You can use SCRAM to authenticate to MongoDB Atlas, MongoDB Enterprise Advanced, and MongoDB Community Edition.

Tip: SCRAM Mechanisms

To learn more about the SCRAM family of authentication mechanisms, see RFC 5802 and Salted Challenge Response Authentication Mechanism on Wikipedia.

For more information about the MongoDB implementation of SCRAM, see SCRAM in the MongoDB Server manual.

Code Placeholders

The code examples on this page use the following placeholders:

  • <db_username>: The MongoDB database username of the user to authenticate.

  • <db_password>: The MongoDB database password of the user to authenticate.

  • <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 a port number when connecting to a MongoDB Atlas cluster.

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

Using SCRAM Authentication in Your Application

To use SCRAM to authenticate your MongoDB user, specify your MongoDB username and password in the connection URI along with the authSource and authMechanism parameters. The examples on this page use authSource=admin, which is the default authentication database, and set authMechanism to either SCRAM-SHA-256 or SCRAM-SHA-1.

You can connect in the following ways:

  • By using a connection URI alone

  • By using a connection URI with Transport Layer Security (TLS) options configured in a mongocxx::options::client object

The following tabs show examples for both SCRAM-SHA-256 and SCRAM-SHA-1, for both TLS and non-TLS connections. Select the tab that matches the authentication mechanism and connection method you want to use.

SCRAM-SHA-256

auto uri = mongocxx::uri("mongodb://<db_username>:<db_password>@<hostname>:<port>/?"
                         "authSource=admin&authMechanism=SCRAM-SHA-256");
auto client = mongocxx::client(uri);

API Documentation

To learn more about creating a mongocxx::client object in C++ driver, see the following API documentation: