Authentication Mechanisms身份验证机制
On this page本页内容
In this guide, you can find sample code for connection to MongoDB with each authentication mechanism available in the MongoDB Community Edition: 在本指南中,您可以找到连接到MongoDB的示例代码,其中包含MongoDB Community Edition中提供的每种身份验证机制:DEFAULT
, SCRAM-SHA-256
, SCRAM-SHA-1
, MONGODB-CR
, MONGODB-AWS
, and X.509
.DEFAULT
、SCRAM-SHA-256
、SCRAM-SHA-1
、MongoDB-CR
、MongoDB-AWS
和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:DEFAULT
身份验证机制是一种回退设置,指示驱动程序按照以下首选顺序协商服务器支持的第一个身份验证机制:
SCRAM-SHA-256
SCRAM-SHA-1
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 如果MongoDB实例的版本不支持该机制,则驱动程序会尝试使用SCRAM-SHA-1
. 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.还包括您的用户名和密码,如下面的代码所示。
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
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 是一种咸挑战响应身份验证机制(SCRAM),它使用您的用户名和密码,并使用SHA-256
algorithm to authenticate your user.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
来指定此身份验证机制,如以下示例代码所示。
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
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 是一种盐水挑战响应机制(SCRAM),使用您的用户名和密码,使用SHA-1
algorithm to authenticate your user.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
来指定此身份验证机制,如以下示例代码所示。
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
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
来指定此选项,如以下示例代码所示。
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);
If you have upgraded the authentication schema from MONGODB-CR to SCRAM, any 如果您已将身份验证模式从MONGODB-CR升级到SCRAM,则任何MONGODB-CR
user authentication requests fail.MONGODB-CR
用户身份验证请求都将失败。
MONGODB-AWS
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如果您还没有AWS签名库, use the following
npm
command to install it:,请使用以下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:驱动程序按顺序在以下来源中检查您的凭据:
Connection string连接字符串Environment variables环境变量Web identity token fileWeb标识令牌文件AWS ECS endpoint specified inAWS_CONTAINER_CREDENTIALS_RELATIVE_URI
中指定的AWS ECS端点AWS EC2 endpoint. For more information, see IAM Roles for TasksAWS EC2终点。有关更多信息,请参阅IAM任务角色.
。
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凭据,则驱动程序将忽略您在环境变量中指定的任何凭据。
Retrieval of AWS CredentialsAWS证书检索
Starting in version 4.11, when you install the optional 从4.11版本开始,当您安装可选的aws-sdk/credential-providers
dependency, the driver uses the AWS SDK to retrieve credentials from the environment. 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在shell中设置AWS_SHARED_CREDENTIALS_FILE
variable in your shell to point to your credentials file.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为MongoDB凭据创建一个AWS配置文件,并将AWS_PROFILE
environment variable to that profile name.AWS_PROFILE
环境变量设置为该配置文件名称。
X.509
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 toMONGODB-X509
authMechanism
参数设置为MONGODB-X509
Set the将tls
parameter totrue
tls
参数设置为true
Pass the location of your client certificate file as the value of 将客户端证书文件的位置作为tlsCertificateKeyFile
as a parameter of the connection URI.tlsCertificateKeyFile
的值作为连接URI的参数传递。
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选项。
tls | boolean | false | |
tlsInsecure | boolean | false | true , this is equivalent to setting tlsAllowInvalidCertificates and tlsAllowInvalidHostnames to true .true ,则相当于将tlsAllowInvalidCertificates 和tlsAllowInvalidHostnames 设置为true 。 |
tlsCAFile | string | ||
tlsCertificateKeyFile | string | ||
tlsCertificateKeyFilePassword | buffer or string | ||
tlsAllowInvalidCertificates | boolean | false | |
tlsAllowInvalidHostnames | boolean | false |