AWS IAM Authentication Mechanism
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.
Tip
Configure Atlas for AWS IAM Authentication
To learn more about configuring MongoDB Atlas for AWS IAM authentication, see Set Up Authentication with AWS IAM in the Atlas documentation.
Specify MONGODB-AWS Authentication
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:
npm install aws4
To connect to a MongoDB instance with MONGODB-AWS
authentication
enabled, specify the MONGODB-AWS
authentication mechanism.
The driver checks for your credentials in the following sources in order:
Connection string
Environment variables
Web identity token file
AWS ECS endpoint specified in
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
AWS EC2 endpoint. For more information, see IAM Roles for Tasks.
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 the connection string, the driver ignores any credentials that you specified in environment variables.
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:
Important
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 = "<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);
To authenticate to your MongoDB instance using AWS credentials stored in environment variables, set the following variables by using a 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.
After you've set the preceding environment variables, specify the MONGODB-AWS
authentication mechanism in your connection string as shown in the following example:
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. 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);
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.
To authenticate with your OIDC token you must first install
@aws-sdk/credential-providers. You can
install this dependency using the following npm
command:
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:
export AWS_WEB_IDENTITY_TOKEN_FILE=<absolute path to file containing your OIDC token>
AWS recommends using regional AWS STS endpoints instead of global endpoints to reduce latency, build-in redundancy, and increase session token validity. To set the AWS region, set AWS_REGION and AWS_STS_REGIONAL_ENDPOINTS as environment variables, as shown in the following example:
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.
Warning
Consult your SDK's Documentation for Setting an AWS Region
You cannot set your AWS region with environment variables for all SDKs, as in the above example. See your SDK's specific documentation for configuring an AWS region.
After you've set the preceding environment variables, specify the MONGODB-AWS
authentication mechanism in your connection string as shown in the following example:
const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. 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);
Important
Retrieval of AWS Credentials
Starting in MongoDB version 4.11, when you install the optional
aws-sdk/credential-providers
dependency, the driver uses the AWS SDK
to retrieve credentials from the environment. As a result, if you
have a shared AWS credentials file or config file, the driver will
use those credentials by default.
You can override this behavior by performing one of the following actions:
Set
AWS_SHARED_CREDENTIALS_FILE
variable in your shell to point to your 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
AWS_PROFILE
environment variable to that profile name.
API Documentation
To learn more about any of the methods or types discussed on this page, see the following API documentation: