Docs Home / Node.js Driver / Authentication

AWS IAM Authentication MechanismAWS IAM身份验证机制

Overview概述

The MONGODB-AWS authentication mechanism uses Amazon Web Services Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. You can use this mechanism only when authenticating to MongoDB Atlas.MONGODB-AWS身份验证机制使用Amazon Web Services身份和访问管理(AWS IAM)凭据对MONGODB的用户进行身份验证。您只能在向MongoDB Atlas进行身份验证时使用此机制。

Tip

Configure Atlas for AWS IAM Authentication为AWS IAM身份验证配置Atlas

To learn more about configuring MongoDB Atlas for AWS IAM authentication, see Set Up Authentication with AWS IAM in the Atlas documentation.要了解有关为AWS IAM身份验证配置MongoDB Atlas的更多信息,请参阅Atlas文档中的“使用AWS IAM设置身份验证”

Specify MONGODB-AWS Authentication指定MONGODB-AWS身份验证

The MONGODB-AWS authentication mechanism uses your Amazon Web Services Identity and Access Management (AWS IAM) credentials to authenticate your user. If you do not already have the AWS signature library, use the following npm command to install it:MONGODB-AWS身份验证机制使用您的Amazon Web Services身份和访问管理(AWS IAM)凭据对您的用户进行身份验证。如果您还没有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-WS身份验证机制。

The driver checks for your credentials in the following sources in order:驱动程序按顺序在以下来源中检查您的凭据:

  1. Custom credential provider (if provided to the MongoClient)自定义凭据提供程序(如果提供给MongoClient
  2. Environment variables available through process.env通过process.env可用的环境变量
  3. SSO credentials from the token cache来自令牌缓存的SSO凭据
  4. Web identity token credentials through the AWS_WEB_IDENTITY_TOKEN_FILE通过AWS_WEB_IDENTITY_TOKEN_FILE获取Web身份令牌凭据
  5. Shared credentials and config .ini files共享凭据和配置.ini文件
  6. EC2 or ECS Instance Metadata Service. For more information, see IAM Roles for Tasks.EC2或ECS实例元数据服务。有关更多信息,请参阅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 environment variables, the driver ignores any credentials that you specified in a web identity token file.驱动程序仅按照前面列表给出的顺序从它检测到的第一个方法中读取凭据。例如,如果您在环境变量中指定了AWS凭据,则驱动程序会忽略您在web身份令牌文件中指定的任何凭据。

Environment Variables环境变量

To authenticate to your MongoDB instance using AWS credentials stored in environment variables available through process.env, set the following variables by using a shell:要使用存储在processenv环境变量中的AWS凭据对MongoDB实例进行身份验证,请使用shell设置以下变量:

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

Note

Omit the line containing AWS_SESSION_TOKEN if you don't need an AWS session token for that role.如果您不需要该角色的AWS会话令牌,请省略包含AWS_SESSION_TOKEN的行。

AWS recommends using regional AWS STS endpoints instead of global endpoints to reduce latency, build-in redundancy, and increase session token validity. AWS建议使用区域AWS STS端点而不是全局端点,以减少延迟、内置冗余并提高会话令牌有效性。To set the AWS region, set AWS_REGION and AWS_STS_REGIONAL_ENDPOINTS as environment variables, as shown in the following example:要设置AWS区域,请将AWS_REGIONAWS_STS_REGIONAL_ENDPOINTS设置为环境变量,如下例所示:

export AWS_STS_REGIONAL_ENDPOINTS=regional // Enables regional endpoints
export AWS_REGION=us-east-1 // Sets your AWS region

If both these environment variables aren't set, the default region is us-east-1. For a list of available AWS regions, see the Regional Endpoints section of the AWS Service Endpoints reference in the AWS documentation.如果这两个环境变量都没有设置,则默认区域为us-east-1。有关可用AWS区域的列表,请参阅AWS文档中AWS服务端点参考的区域端点部分。

After you've set the preceding environment variables, specify the MONGODB-AWS authentication mechanism in your connection string as shown in the following example:设置完上述环境变量后,在连接字符串中指定MONGODB-AWS身份验证机制,如下例所示:

const { MongoClient } = require("mongodb");

// Remember to specify your AWS credentials in environment variables.请记住在环境变量中指定您的AWS凭据。
const clusterUrl = "<cluster_url>";
const authMechanism = "MONGODB-AWS";

let uri =
`mongodb+srv://${clusterUrl}/?authSource=%24external&authMechanism=${authMechanism}`;

// Create a new MongoClient.创建一个新的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 Identity Token FileWeb身份令牌文件

You can use the OpenID Connect (OIDC) token obtained from a web identity provider to authenticate to Amazon Elastic Kubernetes Service (EKS) or other services.您可以使用从web身份提供者获得的OpenID Connect(OIDC)令牌对Amazon Elastic Kubernetes Service(EKS)或其他服务进行身份验证。

To authenticate with your OIDC token you must first install @aws-sdk/credential-providers. You can install this dependency using the following npm command:要使用OIDC令牌进行身份验证,您必须首先安装@aws-sdk/credential-providers提供程序。您可以使用以下npm命令安装此依赖关系:

npm install @aws-sdk/credential-providers

Next, create a file that contains your OIDC token. Then set the absolute path to this file in an environment variable by using a shell as shown in the following example:接下来,创建一个包含OIDC令牌的文件。然后使用shell在环境变量中设置此文件的绝对路径,如下例所示:

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

After you've set the preceding environment variable, specify the MONGODB-AWS authentication mechanism in your connection string as shown in the following example:设置完上述环境变量后,在连接字符串中指定MONGODB-AWS身份验证机制,如下例所示:

const { MongoClient } = require("mongodb");

// Remember to specify your AWS credentials in environment variables.请记住在环境变量中指定您的AWS凭据。
const clusterUrl = "<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 {
// 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);

Manually Specify AWS Credentials手动指定AWS凭据

When you install the optional aws-sdk/credential-providers dependency, the driver retrieves credentials in a priority order defined by the AWS SDK. If you have a shared AWS credentials file or config file, the driver uses those credentials by default.安装可选的aws-sdk/credential-providers依赖关系时,驱动程序将按照AWS SDK定义的优先级顺序检索凭据。如果您有共享的AWS凭据文件或配置文件,则驱动程序默认使用这些凭据。

Tip

To learn more about how the aws-sdk/credential-providers dependency retrieves credentials, see the AWS SDK documentation.要了解有关aws-sdk/credential-providers依赖关系如何检索凭据的更多信息,请参阅AWS SDK文档

To manually specify the AWS credentials to retrieve, you can set the AWS_CREDENTIAL_PROVIDER property to a defined credential provider from the AWS SDK. The following example passes a provider chain from the AWS SDK to the AWS authentication mechanism:要手动指定要检索的AWS凭据,您可以将AWS_CREDENTIAL_PROVIDER属性设置为AWS SDK中定义的凭据提供程序。以下示例将提供者链从AWS SDK传递到AWS身份验证机制:

const { MongoClient } = require('mongodb');
const { fromNodeProviderChain } = require('@aws-sdk/credential-providers');

const client = new MongoClient('<cluster_url>?authMechanism=MONGODB-AWS', {
authMechanismProperties: {
AWS_CREDENTIAL_PROVIDER: fromNodeProviderChain()
}
});

To use a custom provider, you can pass any asynchronous function that returns your credentials to the AWS_CREDENTIAL_PROVIDER authentication mechanism property. The following example shows how to pass a custom provider function that fetches credentials from environment variables to the AWS authentication mechanism:要使用自定义提供程序,您可以将任何将凭据返回给AWS_CREDENTIAL_PROVIDER身份验证机制属性的异步函数传递。以下示例显示了如何将从环境变量获取凭据的自定义提供程序函数传递给AWS身份验证机制:

const { MongoClient } = require('mongodb');

const client = new MongoClient('<cluster_url>?authMechanism=MONGODB-AWS', {
authMechanismProperties: {
AWS_CREDENTIAL_PROVIDER: async () => {
return {
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
}
}
}
});

A custom credential provider takes precedence over any other form of authentication.自定义凭据提供程序优先于任何其他形式的身份验证。

API Documentation文档

To learn more about any of the methods or types discussed on this page, see the following API documentation:要了解有关本页中讨论的任何方法或类型的更多信息,请参阅以下API文档: