Docs HomeNode.js

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 Community Edition中提供的每种身份验证机制:DEFAULTSCRAM-SHA-256SCRAM-SHA-1MongoDB-CRMongoDB-AWSX.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: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创建一个新的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.有关MongoDB支持的质询-响应(CR)和盐水质询-响应身份验证机制(SCRAM)的更多信息,请参阅手册的SCRAM部分。

SCRAM-SHA-256

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.是一种咸挑战响应身份验证机制(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 {
// 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.是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.是一种盐水挑战响应机制(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 {
// 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.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.是一种质询-响应身份验证机制,使用您的用户名和密码对用户进行身份验证。

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 {
// 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用户身份验证请求都将失败。

MONGODB-AWS

Note

The MONGODB-AWS authentication mechanism is available only 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身份验证机制使用您的亚马逊网络服务身份和访问管理(AWS IAM)凭据来验证您的用户。If you do not already have the AWS signature library, use the following npm command to install it:如果您还没有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. Web identity token fileWeb标识令牌文件
  4. AWS ECS endpoint specified in AWS_CONTAINER_CREDENTIALS_RELATIVE_URI中指定的AWS ECS端点
  5. AWS EC2 endpoint. For more information, see IAM Roles for Tasks.AWS EC2终点。有关更多信息,请参阅IAM任务角色
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.例如,如果您在连接字符串中指定AWS凭据,则驱动程序将忽略您在环境变量中指定的任何凭据。

Important

Retrieval of AWS CredentialsAWS证书检索

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. 从4.11版本开始,当您安装可选的aws-sdk/credential-providers依赖项时,驱动程序将使用aws sdk从环境中检索凭据。As a result, if you have a shared AWS credentials file or config file, the driver will use those credentials by default.因此,如果您有一个共享的AWS凭据文件或配置文件,驱动程序将默认使用这些凭据。

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.在shell中设置AWS_SHARED_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.为MongoDB凭据创建一个AWS配置文件,并将AWS_PROFILE环境变量设置为该配置文件名称。

X.509

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 by retrieving the distinguished name (DN) from the client certificate.X.509身份验证机制通过从客户端证书中检索可分辨名称(DN),使用带有X.509证书的TLS进行身份验证。

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

  • Set the authMechanism parameter to MONGODB-X509authMechanism参数设置为MONGODB-X509
  • Set the tls parameter to 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 certificate file path using the encodeURIComponent method to ensure it is parsed correctly.始终使用encodeURIComponent方法对证书文件路径进行URI编码,以确保正确解析。

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.将以下内容替换为MongoDB部署的连接字符串。
const uri =
`mongodb+srv://${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 {
// 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);

TLS/SSL OptionsTLS/SSL选项

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描述
tlsbooleanfalseSpecifies whether to use TLS/SSL connections.指定是否使用TLS/SSL连接。
tlsInsecurebooleanfalseSpecifies 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
tlsCAFilestringPath to file that contains a single or bundle of trusted certificate authorities used in a TLS connection.包含TLS连接中使用的单个或多个受信任证书颁发机构的文件的路径。
tlsCertificateKeyFilestringPath to the client certificate file or the client private key file. 客户端证书文件或客户端私钥文件的路径。If both are required, the two must be concatenated into a single file.如果两者都是必需的,则必须将两者连接到一个文件中。
tlsCertificateKeyFilePasswordbuffer or stringString or buffer that contains the password to decrypt the client private key.包含用于解密客户端私钥的密码的字符串或缓冲区。
tlsAllowInvalidCertificatesbooleanfalseSpecifies whether the driver permits an invalid certificate to be used to connect.指定驱动程序是否允许使用无效证书进行连接。
tlsAllowInvalidHostnamesbooleanfalseSpecifies whether the driver should permit a mismatch between the server hostname and TLS certificate hostname.指定驱动程序是否应允许服务器主机名和TLS证书主机名不匹配。