Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序
/ /

身份验证机制

在此页面上

  • DEFAULT
  • SCRAM-SHA-256
  • SCRAM-SHA-1
  • MONGODB-CR
  • MONGODB-AWS
  • X.509
  • TLS 选项

在本指南中,您可找到使用 MongoDB Community Edition 中提供的每种身份验证机制连接到 MongoDB 的样本代码:DEFAULTSCRAM-SHA-256SCRAM-SHA-1MONGODB-CRMONGODB-AWSX.509

DEFAULT 身份验证机制是一种后备设置,指示驱动程序按以下优先顺序协商服务器支持的第一个身份验证机制:

  1. SCRAM-SHA-256

  2. SCRAM-SHA-1

  3. MONGODB-CR

如果指定了 DEFAULT 选项,则驱动程序将首先尝试使用 SCRAM-SHA-256 进行身份验证。如果 MongoDB 实例的版本不支持该机制,则驱动程序将尝试使用 SCRAM-SHA-1 进行身份验证。如果实例也不支持该机制,则驱动程序将尝试使用 MONGODB-CR 进行身份验证。

您可以通过在连接字符串中将authMechanism参数设置为DEFAULT来指定此身份验证机制,也可以省略该参数,因为它是默认值。此外,请按以下代码所示输入用户名和密码。

重要

始终使用 encodeURIComponent 方法对用户名和密码进行 URI 编码,以确保正确解析它们。

const { MongoClient } = require("mongodb");
// Replace the following with values for your environment.
const username = encodeURIComponent("<db_username>");
const password = encodeURIComponent("<db_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 {
// 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) 和加盐质询-响应身份验证机制 (SCRAM) 的更多信息,请参阅手册的SCRAM部分。

注意

SCRAM-SHA-256 是从 MongoDB 4.0 开始使用的默认身份验证方法

SCRAM-SHA-256 是一种盐值挑战 — 响应身份验证机制 (SCRAM),使用用 SHA-256 算法加密的用户名和密码来验证用户身份。

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

重要

始终使用 encodeURIComponent 方法对用户名和密码进行 URI 编码,以确保正确解析它们。

const { MongoClient } = require("mongodb");
// Replace the following with values for your environment.
const username = encodeURIComponent("<db_username>");
const password = encodeURIComponent("<db_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 {
// 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 是 MongoDB 版本 3.0、3.2、3.4 和 3.6 的默认身份验证方法。

SCRAM-SHA-1 是一种盐化质询-响应机制 (SCRAM),它使用您的用户名和密码,并通过 SHA-1 算法加密,来对您的用户进行身份验证。

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

重要

始终使用 encodeURIComponent 方法对用户名和密码进行 URI 编码,以确保正确解析它们。

const { MongoClient } = require("mongodb");
// Replace the following with values for your environment.
const username = encodeURIComponent("<db_username>");
const password = encodeURIComponent("<db_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 {
// 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 3.6 开始已弃用,并从 MongoDB 4.0 起不再受支持

MONGODB-CR 是一种挑战-响应身份验证机制,它使用您的用户名和密码 来验证您的用户。

您可以通过在连接字符串中将authMechanism参数设置为值MONGODB-CR来指定此选项,如以下示例代码所示。

重要

始终使用 encodeURIComponent 方法对用户名和密码进行 URI 编码,以确保正确解析它们。

const { MongoClient } = require("mongodb");
// Replace the following with values for your environment.
const username = encodeURIComponent("<db_username>");
const password = encodeURIComponent("<db_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 {
// 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 升级到 SCRAM,则所有 MONGODB-CR 用户身份验证请求都会失败。

注意

MONGODB-AWS 身份验证机制仅适用于 MongoDB 4.4 及更高版本。

MONGODB-AWS 身份验证机制使用 Amazon Web Services Identity and Access Management (AWS IAM) 凭证对用户进行身份验证。如果你还没有 AWS 签名库,则使用以下 npm 命令进行安装:

npm install aws4

要连接到启用了 MONGODB-AWS 身份验证的 MongoDB 实例,请指定 MONGODB-AWS 身份验证机制。

驱动程序会按顺序在以下来源中检查是否存在您的档案:

  1. 连接字符串

  2. 环境变量

  3. 网络身份令牌文件

  4. AWS ECS 端点 AWS_CONTAINER_CREDENTIALS_RELATIVE_URI

  5. AWS EC2 端点。有关更多信息,请参阅针对任务的 IAM 角色

重要

驱动程序只会按照上述列表中的顺序,从其检测到的第一个方法读取凭证。例如,如果您在连接字符串中指定了 AWS 凭证,则驱动程序将忽略您在环境变量中指定的任何凭证。

要使用连接字符串连接到 MongoDB 实例,请在尝试连接时将您的 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY 档案传递给驱动程序。如果您的 AWS 登录需要会话令牌,请同时包含您的 AWS_SESSION_TOKEN

以下代码显示了使用连接字符串指定 MONGODB-AWS 身份验证机制和档案的示例:

重要

始终使用 encodeURIComponent 方法对用户名和证书文件路径进行 URI 编码,以确保对其进行正确解析。

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 {
// 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);

MongoDBAmazon Web Services要使用存储在环境变量中的 档案对 实例进行身份验证,请使用shell 设置以下变量:

export AWS_ACCESS_KEY_ID=<awsKeyId>
export AWS_SECRET_ACCESS_KEY=<awsSecretKey>
export AWS_SESSION_TOKEN=<awsSessionToken>

注意

如果您不需要该角色的 AWS 会话令牌,请省略包含AWS_SESSION_TOKEN的行。

设置上述环境变量后,在连接string中指定 MONGODB-AWS 身份验证机制,如以下示例所示:

const { MongoClient } = require("mongodb");
// Remember to specify your AWS credentials in environment variables.
const clusterUrl = "<MongoDB deployment 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 {
// 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);

您可以使用从 Web 身份提供商获取的 OpenID Connect (OIDC) 令牌对 Amazon Elastic Kubernetes Service (EKS) 或其他服务进行身份验证。

要使用 OIDC 令牌进行身份验证,必须先安装 @aws-sdk/credential-providers 。您可以使用以下npm命令安装此依赖项:

npm install @aws-sdk/credential-providers

接下来,创建一个包含 OIDC 令牌的文件。 然后使用 shell 在环境变量中设置此文件的绝对路径,如以下示例所示:

export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>

设置上述环境变量后,在连接string中指定 MONGODB-AWS 身份验证机制,如以下示例所示:

const { MongoClient } = require("mongodb");
// Remember to specify your AWS credentials in environment variables.
const clusterUrl = "<MongoDB deployment 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 {
// 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);

重要

检索 AWS 档案

从版本 4.11 开始,当您安装可选的 aws-sdk/credential-providers 依赖项时,驱动程序将使用 AWS SDK 从环境中检索凭证。因此,如果您有共享的 AWS 凭证文件或配置文件,驱动程序将默认使用这些凭证。

您可以通过执行下列操作之一来覆盖此行为:

  • 在 shell 中设置 AWS_SHARED_CREDENTIALS_FILE 变量以指向您的档案文件。

  • 在应用程序中设置等效的环境变量以指向您的凭证文件。

  • 为您的 MongoDB 档案创建 AWS 配置文件,并将 AWS_PROFILE 环境变量设置为该配置文件的名称。

注意

X.509 身份验证机制仅适用于 MongoDB 2.6 及更高版本。

X.509 身份验证机制使用带有 X.509 证书的 TLS,通过从客户端证书中检索标识名 (DN) 进行身份验证。

您可以通过设置连接字符串的以下参数来指定此身份验证机制:

  • authMechanism 参数设为 MONGODB-X509

  • tls 参数设为 true

将客户端证书文件的位置作为连接 URI 参数的 tlsCertificateKeyFile 值进行传递。

重要

始终使用 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.
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 {
// 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 的更多信息,请参阅在连接上启用 TLS。

下表描述了您可以在连接 URI 中设置的 TLS 选项。

参数名称
类型
默认值
说明
tls
布尔
false
指定是否对此连接启用 TLS。
tlsInsecure
布尔
false
指定是否允许无效证书和错配的主机名。设置为 true 时,相当于将 tlsAllowInvalidCertificatestlsAllowInvalidHostnames 设置为 true
tlsCAFile
字符串
一个文件的路径,此文件中包含 TLS 连接中使用的单个或一组受信任证的书颁发机构。
tlsCertificateKeyFile
字符串
客户端证书文件或客户端私钥文件的路径。如果同时需要这两份文件,则必须将这两者合并为一个文件。
tlsCertificateKeyFilePassword
缓冲区或字符串
包含密码的字符串或缓冲区,该密码被用来对客户端私钥进行解密。
tlsAllowInvalidCertificates
布尔
false
指定该驱动程序是否允许使用无效证书进行连接。
tlsAllowInvalidHostnames
布尔
false
指定当服务器主机名与 TLS 证书主机名不匹配时,驱动程序是否会引发错误。

后退

身份验证