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.在本指南中,您可以找到连接到MongoDB的示例代码以及MongoDB社区版中提供的每种身份验证机制:DEFAULTSCRAM-SHA-256SCRAM-SHA-1MongoDB-CRMongoDB-AWSX.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:DEFAULT身份验证机制是一种回退设置,指示驱动程序按照以下优先顺序协商服务器支持的第一种身份验证机制:

  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. 如果指定了DEFAULT选项,驱动程序首先尝试使用SCRAM-SHA-256进行身份验证。If the version of the MongoDB instance does not support that mechanism, the driver attempts to authenticate using SCRAM-SHA-1. 如果MongoDB实例的版本不支持该机制,则驱动程序将尝试使用SCRAM-SHA-1进行身份验证。If the instance does not support that mechanism either, the driver attempts to authenticate using MONGODB-CR.如果实例也不支持该机制,则驱动程序将尝试使用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. 可以通过在连接字符串中将authMechanism参数设置为DEFAULT,或者忽略该参数(因为它是默认值),来指定此身份验证机制。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.始终使用encodeURIComponent方法对用户名和密码进行URI编码,以确保正确解析它们。

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.用MongoDB部署的连接字符串替换以下内容。 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.有关MongoDB支持的质询响应(CR)和salt质询响应认证机制(SCRAM)的更多信息,请参阅手册的SCRAM部分。

Note

SCRAM-SHA-256 is the default authentication method for MongoDB starting in version 4.0是从版本4.0开始的MongoDB的默认身份验证方法

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.是一种salted质询-响应身份验证机制(SCRAM),它使用您的用户名和密码,并使用SHA-256算法加密以验证您的用户。

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.您可以通过在连接字符串中将authMechanism设置为值SCRAM-SHA-256来指定此身份验证机制,如以下示例代码所示。

Important

Always URI encode the username and password using the encodeURIComponent method to ensure they are correctly parsed.始终使用encodeURIComponent方法对用户名和密码进行URI编码,以确保正确解析它们。

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.用MongoDB部署的连接字符串替换以下内容。 const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`;
// Create a new MongoClient创建新的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.是MongoDB版本3.0、3.2、3.4和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.是一种salt质询响应机制(SCRAM),它使用您的用户名和密码,并使用SHA-1算法进行加密以验证您的用户。

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.您可以通过将authMechanism参数设置为连接字符串中的值SCRAM-SHA-1来指定此身份验证机制,如以下示例代码所示。

Important

Always URI encode the username and password using the encodeURIComponent method to ensure they are correctly parsed.始终使用encodeURIComponent方法对用户名和密码进行URI编码,以确保正确解析它们。

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.用MongoDB部署的连接字符串替换以下内容。 const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`;
// Create a new MongoClient创建新的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.0MONGODB-CR从MONGODB 3.6开始就被弃用,从MONGODB 4.0开始不再受支持

MONGODB-CR is a challenge-response authentication mechanism that uses your username and password to authenticate your user.MONGODB-CR是一种质询-响应身份验证机制,它使用用户名和密码对用户进行身份验证。

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.您可以通过将authMechanism参数设置为连接字符串中的值MONGODB-CR来指定此选项,如以下示例代码所示。

Important

Always URI encode the username and password using the encodeURIComponent method to ensure they are correctly parsed.始终使用encodeURIComponent方法对用户名和密码进行URI编码,以确保正确解析它们。

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.用MongoDB部署的连接字符串替换以下内容。 const uri = `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`;
// Create a new MongoClient创建新的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.如果已将身份验证架构从MONGODB-CR升级为SCRAM,则任何MONGODB-CR用户身份验证请求都会失败。

Note

The MONGODB-AWS authentication mechanism is only available in MongoDB versions 4.4 and later.MONGODB-AWS认证机制仅在MONGODB版本4.4及更高版本中可用。

The MONGODB-AWS authentication mechanism uses your Amazon Web Services Identity and Access Management (AWS IAM) credentials to authenticate your user. MONGODB-AWS身份验证机制使用您的Amazon Web服务身份和访问管理(AWS IAM)凭据对您的用户进行身份验证。If you do not already have the AWS signature library, install it using the following npm command:如果您还没有AWS签名库,请使用以下npm命令进行安装:

npm install aws4

To connect to a MongoDB instance with MONGODB-AWS authentication enabled, specify the MONGODB-AWS authentication mechanism.要连接到启用MongoDB-AWS身份验证的MongoDB实例,请指定MongoDB-AWS身份验证机制。

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_URIAWS_CONTAINER_CREDENTIALS_RELATIVE_URI中指定的AWS ECS端点
  4. AWS EC2 endpoint. AWS EC2端点。For more information, see IAM Roles for Tasks.有关更多信息,请参阅任务的IAM角色

To connect to your MongoDB instance with environment variables, add your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY credentials to your environment variables. If your AWS login requires an AWS_SESSION_TOKEN, add it to your environment variables as well.

The following code shows an example of specifying the MONGODB-AWS authentication mechanism with environment variables:

Note

You don't need to specify these credentials in your connection URI because the driver automatically retrieves them when you attempt to connect.

const { MongoClient } = require("mongodb");
// Remember to add your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY // credentials to your environment variables. const clusterUrl = "<MongoDB cluster 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 { // 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 { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);

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 { // 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 { // Ensure that the client closes when it finishes/errors. await client.close(); } } run().catch(console.dir);
Note

The X.509 authentication mechanism is only available in MongoDB versions 2.6 and later.X.509身份验证机制仅在MongoDB 2.6及更高版本中可用。

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. X.509身份验证机制使用带有X.509证书的TLS对用户进行身份验证,该用户由客户端证书的可分辨名称(DN)标识。For more information on determining the subject name from the X.509 certificate, see the MongoDB manual X.509 tutorial.有关从X.509证书确定主题名称的更多信息,请参阅MongoDB手册的X.509教程

You can specify this authentication mechanism by setting the following parameters of your connection string:您可以通过设置连接字符串的以下参数来指定此身份验证机制:

  • Set the authMechanism parameter to the value MONGODB-X509authMechanism参数设置为值MONGODB-X509
  • Set the tls parameter to the value truetls参数的值设置为true

Pass the location of your client certificate file as the value of tlsCertificateKeyFile as a parameter of the connection URI.将客户端证书文件的位置作为tlsCertificateKeyFile的值作为连接URI的参数传递。

Important

Always URI encode the username and certificate file path using the encodeURIComponent method to ensure they are correctly parsed.始终使用encodeURIComponent方法对用户名和证书文件路径进行URI编码,以确保正确解析它们。

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.用MongoDB部署的连接字符串替换以下内容。 const uri = `mongodb+srv://${username}@${clusterUrl}/?authMechanism=${authMechanism}&tls=true&tlsCertificateKeyFile=${clientPEMFile}`;
// Create a new MongoClient创建新的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.下表描述了可以作为连接URI中的参数传递的每个TLS/SSL选项。

Parameter Name参数名
Type类型
Default Value默认值
Description描述
tls
boolean
false
Specifies whether to use TLS/SSL connections.指定是否使用TLS/SSL连接。
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.当设置为true时,这相当于将tlsAllowInvalidCertificatestlsAllowInvalidHostnames设置为true
tlsCAFile
string
Path to file that contains a single or bundle of trusted certificate authorities used in a TLS connection.包含TLS连接中使用的单个或多个受信任证书颁发机构的文件的路径。
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.指定驱动程序是否应允许服务器主机名和TLS证书主机名不匹配。