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社区版中提供的每种身份验证机制: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
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部分。
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 是一种salted质询-响应身份验证机制(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 {
// 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);
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 是一种salt质询响应机制(SCRAM),它使用您的用户名和密码,并使用SHA-1算法进行加密以验证您的用户。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.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 {
// 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);
MONGODB-CR
¶
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来指定此选项,如以下示例代码所示。
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);
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 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 如果您还没有AWS签名库,请使用以下npm命令进行安装:npm
command:
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环境变量AWS ECS endpoint specified in在AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
中指定的AWS ECS端点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:
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:
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);
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 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 valueMONGODB-X509
authMechanism
参数设置为值MONGODB-X509
Set the将tls
parameter to the valuetrue
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 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);
TLS/SSL Options¶
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 |