Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Authentication Mechanisms

On this page

  • DEFAULT
  • SCRAM-SHA-256
  • SCRAM-SHA-1
  • MONGODB-CR
  • MONGODB-AWS
  • X.509
  • TLS/SSL Options

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

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.

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("<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);

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("<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

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("<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

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

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. If you do not already have the AWS signature library, install it using the following npm command:

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:

  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.

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.

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 to MONGODB-X509

  • Set the tls parameter to true

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 {
// 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.
←  AuthenticationEnterprise Authentication Mechanisms →