文档菜单
文档首页
/ / /
Node.js 驱动
/ /

身份验证机制

本页内容

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

在本指南中,您可以找到使用MongoDB社区版中提供的每种身份验证机制连接到MongoDB的示例代码默认SCRAM-SHA-256SCRAM-SHA-1MONGODB-CRMONGODB-AWSX.509

默认身份验证机制是一个后备设置,指示驱动程序与服务器协商以下优先级顺序中服务器支持的第一个身份验证机制

  1. SCRAM-SHA-256

  2. SCRAM-SHA-1

  3. MONGODB-CR

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

您可以通过在以下设置中将authMechanism参数设置为默认来指定此身份验证机制连接字符串,或者省略该参数,因为它是默认值。同时,请包括以下代码中所示的用户名和密码。

重要

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

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方法对用户名和密码进行编码,以确保它们被正确解析。

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方法对用户名和密码进行编码,以确保它们被正确解析。

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方法对用户名和密码进行编码,以确保它们被正确解析。

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身份和访问管理(AWS IAM)凭证来认证您的用户。如果您还没有AWS签名库,可以使用以下npm命令来安装它

npm install aws4

要连接到已启用MONGODB-AWS认证的MongoDB实例,请指定MONGODB-AWS认证机制。

驱动程序会按照以下顺序检查您的凭证:

  1. 连接字符串

  2. 环境变量

  3. Web身份令牌文件

  4. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI中指定的AWS ECS端点

  5. AWS EC2端点。更多信息,请参阅IAM Roles for Tasks

重要

驱动程序仅从它检测到的第一个方法中读取凭证,顺序与前面列表中给出的顺序相同。例如,如果您在连接字符串中指定了您的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);

要使用存储在环境变量中的AWS凭证对MongoDB实例进行认证,请使用shell设置以下变量

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

注意

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

设置完前面的环境变量后,如以下示例所示,在您的连接字符串中指定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>

设置完前面的环境变量后,如以下示例所示,在您的连接字符串中指定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证书通过从客户端证书检索区分名称(DN)进行认证的X.509认证机制与TLS进行认证。

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

  • authMechanism参数设置为MONGODB-X509

  • tls参数设置为true

将客户端证书文件的路径作为连接URI的参数传递给tlsCertificateKeyFile

重要

始终使用encodeURIComponent方法对证书文件路径进行URL编码,以确保它被正确解析。

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证书主机名不匹配时,驱动程序是否引发错误。

返回

身份验证