Authentication Mechanisms
In this guide, you can find sample code for connection to MongoDB with each
authentication mechanism available in the MongoDB Community Edition:
DEFAULT
, SCRAM-SHA-256
, SCRAM-SHA-1
, MONGODB-CR
,
MONGODB-AWS
, and X.509
.
DEFAULT
The DEFAULT
authentication mechanism is a fallback setting that instructs
the driver to negotiate the first authentication mechanism supported by the
server in the following order of preference:
SCRAM-SHA-256
SCRAM-SHA-1
MONGODB-CR
If the DEFAULT
option is specified, the driver first attempts to
authenticate using SCRAM-SHA-256
. If the version of the MongoDB instance
does not support that mechanism, the driver attempts to authenticate using
SCRAM-SHA-1
. If the instance does not support that mechanism either,
the driver attempts to authenticate using MONGODB-CR
.
You can specify this authentication mechanism by setting the authMechanism
parameter to DEFAULT
in the
connection string, or by omitting
the parameter since it is the default value. Also include your username and
password as shown in the code below.
Important
Always URI encode the username and password using the
encodeURIComponent
method to ensure they are correctly parsed.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "DEFAULT"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
For more information on the challenge-response (CR) and salted challenge-response authentication mechanisms (SCRAM) that MongoDB supports, see the SCRAM section of the manual.
SCRAM-SHA-256
Note
SCRAM-SHA-256
is the default authentication method for MongoDB starting
in version 4.0
SCRAM-SHA-256
is a salted challenge-response authentication mechanism
(SCRAM) that uses your username and password, encrypted with the SHA-256
algorithm to authenticate your user.
You can specify this authentication mechanism by setting the authMechanism
to the value SCRAM-SHA-256
in the
connection string as shown in the
following sample code.
Important
Always URI encode the username and password using the
encodeURIComponent
method to ensure they are correctly parsed.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "SCRAM-SHA-256"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
SCRAM-SHA-1
Note
SCRAM-SHA-1
is the default authentication method for MongoDB versions
3.0, 3.2, 3.4, and 3.6.
SCRAM-SHA-1
is a salted challenge-response mechanism (SCRAM) that uses your
username and password, encrypted with the SHA-1
algorithm to authenticate
your user.
You can specify this authentication mechanism by setting the authMechanism
parameter to the value SCRAM-SHA-1
in the
connection string as shown
in the following sample code.
Important
Always URI encode the username and password using the
encodeURIComponent
method to ensure they are correctly parsed.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "SCRAM-SHA-1"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
MONGODB-CR
Warning
MONGODB-CR was deprecated starting in MongoDB 3.6, and is no longer supported as of MongoDB 4.0
MONGODB-CR
is a challenge-response authentication mechanism that uses your
username and password to authenticate your user.
You can specify this option by setting the authMechanism
parameter to value
MONGODB-CR
in the
connection string as shown
in the following sample code.
Important
Always URI encode the username and password using the
encodeURIComponent
method to ensure they are correctly parsed.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent("<db_username>"); const password = encodeURIComponent("<db_password>"); const clusterUrl = "<MongoDB cluster url>"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Important
If you have upgraded the authentication schema from MONGODB-CR to
SCRAM, any MONGODB-CR
user
authentication requests fail.
MONGODB-AWS
Note
The MONGODB-AWS authentication mechanism is available only in MongoDB versions 4.4 and later.
The MONGODB-AWS
authentication mechanism uses your Amazon Web Services
Identity and Access Management (AWS IAM) credentials to authenticate your
user. If you do not already have the AWS signature library, use the following
npm
command to install it:
npm install aws4
To connect to a MongoDB instance with MONGODB-AWS
authentication
enabled, specify the MONGODB-AWS
authentication mechanism.
The driver checks for your credentials in the following sources in order:
Connection string
Environment variables
Web identity token file
AWS ECS endpoint specified in
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
AWS EC2 endpoint. For more information, see IAM Roles for Tasks.
Important
The driver only reads the credentials from the first method that it detects in the order as given by the preceding list. For example, if you specify your AWS credentials in the connection string, the driver ignores any credentials that you specified in environment variables.
To connect to your MongoDB instance with a connection string, pass
your AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
credentials to the driver when you attempt to connect. If your AWS
login requires a session token, include your AWS_SESSION_TOKEN
as well.
The following code shows an example of specifying the MONGODB-AWS
authentication mechanism and credentials with a connection string:
Important
Always URI encode the username and certificate file path using the
encodeURIComponent
method to ensure they are correctly parsed.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const accessKeyId = encodeURIComponent("<AWS_ACCESS_KEY_ID>"); const secretAccessKey = encodeURIComponent("<AWS_SECRET_ACCESS_KEY>"); const clusterUrl = "<MongoDB cluster url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${accessKeyId}:${secretAccessKey}@${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Uncomment the following lines if your AWS authentication setup requires a session token. // const sessionToken = encodeURIComponent("<AWS_SESSION_TOKEN>"); // uri = uri.concat(`&authMechanismProperties=AWS_SESSION_TOKEN:${sessionToken}`); // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
To authenticate to your MongoDB instance using AWS credentials stored in environment variables, set the following variables by using a shell:
export AWS_ACCESS_KEY_ID=<awsKeyId> export AWS_SECRET_ACCESS_KEY=<awsSecretKey> export AWS_SESSION_TOKEN=<awsSessionToken>
Note
Omit the line containing AWS_SESSION_TOKEN
if you don't need an AWS
session token for that role.
After you've set the preceding environment variables, specify the MONGODB-AWS
authentication mechanism in your connection string as shown in the following example:
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. const clusterUrl = "<MongoDB deployment url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
You can use the OpenID Connect (OIDC) token obtained from a web identity provider to authenticate to Amazon Elastic Kubernetes Service (EKS) or other services.
To authenticate with your OIDC token you must first install
@aws-sdk/credential-providers. You can
install this dependency using the following npm
command:
npm install @aws-sdk/credential-providers
Next, create a file that contains your OIDC token. Then set the absolute path to this file in an environment variable by using a shell as shown in the following example:
export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>
After you've set the preceding environment variable, specify the MONGODB-AWS
authentication mechanism in your connection string as shown in the following example:
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. const clusterUrl = "<MongoDB deployment url>"; const authMechanism = "MONGODB-AWS"; let uri = `mongodb+srv://${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`; // Create a new MongoClient. const client = new MongoClient(uri); async function run() { try { // Establish and verify connection. await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server."); } finally { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
Important
Retrieval of AWS Credentials
Starting in version 4.11, when you install the optional
aws-sdk/credential-providers
dependency, the driver uses the AWS SDK
to retrieve credentials from the environment. As a result, if you
have a shared AWS credentials file or config file, the driver will
use those credentials by default.
You can override this behavior by performing one of the following actions:
Set
AWS_SHARED_CREDENTIALS_FILE
variable in your shell to point to your credentials file.Set the equivalent environment variable in your application to point to your credentials file.
Create an AWS profile for your MongoDB credentials and set the
AWS_PROFILE
environment variable to that profile name.
X.509
Note
The X.509 authentication mechanism is only available in MongoDB versions 2.6 and later.
The X.509
authentication mechanism uses
TLS with X.509 certificates to
authenticate by retrieving the distinguished name (DN) from the
client certificate.
You can specify this authentication mechanism by setting the following parameters of your connection string:
Set the
authMechanism
parameter toMONGODB-X509
Set the
tls
parameter totrue
Pass the location of your client certificate file as the value of
tlsCertificateKeyFile
as a parameter of the connection URI.
Important
Always URI encode the certificate file path using the
encodeURIComponent
method to ensure it is parsed correctly.
const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const clusterUrl = "<MongoDB cluster url>"; const clientPEMFile = encodeURIComponent("<path to the client pem certificate file>"); const authMechanism = "MONGODB-X509"; // Replace the following with your MongoDB deployment's connection string. const uri = `mongodb+srv://${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`; // Create a new MongoClient const client = new MongoClient(uri); // Function to connect to the server async function run() { try { // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Tip
To learn more about enabling TLS on a connection, see Enable TLS on a Connection.
TLS Options
The following table describes the TLS options that you can set in a connection URI.
Parameter Name | Type | Default Value | Description |
---|---|---|---|
tls | boolean | false | Specifies whether to enable TLS on the connection. |
tlsInsecure | boolean | false | Specifies whether to allow invalid certificates and mismatched
hostnames. When set to true , this is equivalent to setting
tlsAllowInvalidCertificates and tlsAllowInvalidHostnames to
true . |
tlsCAFile | string | Path to file that contains a single or bundle of trusted certificate
authorities used in a TLS connection. | |
tlsCertificateKeyFile | string | Path to the client certificate file or the client private key file. If
both are required, the two must be concatenated into a single file. | |
tlsCertificateKeyFilePassword | buffer or string | String or buffer that contains the password to decrypt the client
private key. | |
tlsAllowInvalidCertificates | boolean | false | Specifies whether the driver permits an invalid certificate to be used
to connect. |
tlsAllowInvalidHostnames | boolean | false | Specifies whether the driver raises an error when there is a mismatch between the
server hostname and TLS certificate hostname. |