Navigation

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.

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:

  1. SCRAM-SHA-256
  2. SCRAM-SHA-1
  3. 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 With Circle IconCreated with Sketch.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("<username>");
const password = encodeURIComponent("<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 {
// Connect the client to the server
await client.connect();
// 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.

Info With Circle IconCreated with Sketch.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 With Circle IconCreated with Sketch.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("<username>");
const password = encodeURIComponent("<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 {
// Connect the client to the server
await client.connect();
// 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);
Info With Circle IconCreated with Sketch.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 With Circle IconCreated with Sketch.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("<username>");
const password = encodeURIComponent("<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 {
// Connect the client to the server
await client.connect();
// 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);
Warning IconCreated with Sketch.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 With Circle IconCreated with Sketch.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("<username>");
const password = encodeURIComponent("<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 {
// Connect the client to the server
await client.connect();
// 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 With Circle IconCreated with Sketch.Important

If you have upgraded the authentication schema from MONGODB-CR to SCRAM, any MONGODB-CR user authentication requests fail.

Info With Circle IconCreated with Sketch.Note

The MONGODB-AWS authentication mechanism is only available 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.

To connect to a MongoDB instance with MONGODB-AWS authentication enabled, specify the MONGODB-AWS authentication mechanism and 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, you must include your AWS_SESSION_TOKEN as well.

The driver checks the following sources for your credentials in order:

  1. Connection string
  2. Environment variables
  3. AWS ECS endpoint specified in AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
  4. AWS EC2 endpoint. For more information, see IAM Roles for Tasks.

If you do not already have the aws signature library, install it using the following npm command:

npm install aws4

The following code shows an example of specifying the MONGODB-AWS authentication mechanism and credentials in the connection string.

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";
// Replace the following with your MongoDB deployment's connection string.
const uri =
`mongodb+srv://${accessKeyId}:${secretAccessKey}@${clusterUrl}/?authMechanism=${authMechanism}`;
// Create a new MongoClient
const client = new MongoClient(uri);
// Function to connect to the server
async function run() {
try {
// Connect the client to the server
await client.connect();
// 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);
Info With Circle IconCreated with Sketch.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 your user, identified by the distinguished name (DN) of your client certificate. For more information on determining the subject name from the X.509 certificate, see the MongoDB manual X.509 tutorial.

You can specify this authentication mechanism by setting the following parameters of your connection string:

  • Set the authMechanism parameter to the value MONGODB-X509
  • Set the tls parameter to the value true

Pass the location of your client certificate file as the value of tlsCertificateKeyFile as a parameter of the connection URI.

Important With Circle IconCreated with Sketch.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 username = encodeURIComponent("<client certificate distinguished name>");
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://${username}@${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 {
// Connect the client to the server
await client.connect();
// 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);

The following table describes each of the TLS/SSL options that can be passed as a parameter in the connection URI.

Parameter Name
Type
Default Value
Description
tls
boolean
false
Specifies whether to use TLS/SSL connections.
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 should permit a mismatch between the server hostname and TLS certificate hostname.
Give Feedback