3.685.0 • Published 21 days ago

@aws-sdk/credential-providers v3.685.0

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
21 days ago

@aws-sdk/credential-providers

NPM version NPM downloads

A collection of all credential providers, with default clients.

Table of Contents

  1. From Cognito Identity
  2. From Cognito Identity Pool
  3. From Temporary Credentials
  4. From Web Token
    1. Examples
  5. From Token File
  6. From Instance and Container Metadata Service
  7. From HTTP(S)
  8. From Shared INI files
    1. Sample Files
  9. From Environmental Variables
  10. From Credential Process
    1. Sample files
  11. From Single Sign-On Service
    1. Supported Configuration
    2. SSO login with AWS CLI
    3. Sample Files
  12. From Node.js default credentials provider chain
  13. Creating a custom credentials chain

fromCognitoIdentity()

  • Uses @aws-sdk/client-cognito-identity
  • Available in browsers & native apps

The function fromCognitoIdentity() returns CredentialsProvider that retrieves credentials for the provided identity ID. See GetCredentialsForIdentity API for more information.

import { fromCognitoIdentity } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromCognitoIdentity } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  region,
  credentials: fromCognitoIdentity({
    // Required. The unique identifier for the identity against which credentials
    // will be issued.
    identityId: "us-east-1:128d0a74-c82f-4553-916d-90053example",
    // Optional. The ARN of the role to be assumed when multiple roles were received in the token
    // from the identity provider.
    customRoleArn: "arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity",
    // Optional. A set of name-value pairs that map provider names to provider tokens.
    // Required when using identities associated with external identity providers such as Facebook.
    logins: {
      "graph.facebook.com": "FBTOKEN",
      "www.amazon.com": "AMAZONTOKEN",
      "accounts.google.com": "GOOGLETOKEN",
      "api.twitter.com": "TWITTERTOKEN'",
      "www.digits.com": "DIGITSTOKEN",
    },
    // Optional. Custom client config if you need overwrite default Cognito Identity client
    // configuration.
    clientConfig: { region },
  }),
});

fromCognitoIdentityPool()

  • Uses @aws-sdk/client-cognito-identity
  • Available in browsers & native apps

The function fromCognitoIdentityPool() returns AwsCredentialIdentityProvider that calls GetId API to obtain an identityId, then generates temporary AWS credentials with GetCredentialsForIdentity API, see fromCognitoIdentity().

Results from GetId are cached internally, but results from GetCredentialsForIdentity are not.

import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromCognitoIdentityPool } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  region,
  credentials: fromCognitoIdentityPool({
    // Required. The unique identifier for the identity pool from which an identity should be
    // retrieved or generated.
    identityPoolId: "us-east-1:1699ebc0-7900-4099-b910-2df94f52a030",
    // Optional. A standard AWS account ID (9+ digits)
    accountId: "123456789",
    // Optional. A cache in which to store resolved Cognito IdentityIds.
    cache: custom_storage,
    // Optional. A unique identifier for the user used to cache Cognito IdentityIds on a per-user
    // basis.
    userIdentifier: "user_0",
    // Optional. The ARN of the role to be assumed when multiple roles were received in the token
    // from the identity provider.
    customRoleArn: "arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity",
    // Optional. A set of name-value pairs that map provider names to provider tokens.
    // Required when using identities associated with external identity providers such as Facebook.
    logins: {
      "graph.facebook.com": "FBTOKEN",
      "www.amazon.com": "AMAZONTOKEN",
      "accounts.google.com": "GOOGLETOKEN",
      "api.twitter.com": "TWITTERTOKEN",
      "www.digits.com": "DIGITSTOKEN",
    },
    // Optional. Custom client config if you need overwrite default Cognito Identity client
    // configuration.
    clientConfig: { region },
  }),
});

fromTemporaryCredentials()

  • Uses @aws-sdk/client-sts
  • Available in browsers & native apps

The function fromTemporaryCredentials returns AwsCredentialIdentityProvider that retrieves temporary credentials from STS AssumeRole API.

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromTemporaryCredentials } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  region,
  credentials: fromTemporaryCredentials({
    // Optional. The master credentials used to get and refresh temporary credentials from AWS STS.
    // If skipped, it uses the default credential resolved by internal STS client.
    masterCredentials: fromTemporaryCredentials({
      params: { RoleArn: "arn:aws:iam::1234567890:role/RoleA" },
    }),
    // Required. Options passed to STS AssumeRole operation.
    params: {
      // Required. ARN of role to assume.
      RoleArn: "arn:aws:iam::1234567890:role/RoleB",
      // Optional. An identifier for the assumed role session. If skipped, it generates a random
      // session name with prefix of 'aws-sdk-js-'.
      RoleSessionName: "aws-sdk-js-123",
      // Optional. The duration, in seconds, of the role session.
      DurationSeconds: 3600,
      // ... For more options see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
    },
    // Optional. Custom STS client configurations overriding the default ones.
    clientConfig: { region },
    // Optional. A function that returns a promise fulfilled with an MFA token code for the provided
    // MFA Serial code. Required if `params` has `SerialNumber` config.
    mfaCodeProvider: async (mfaSerial) => {
      return "token";
    },
  }),
});

fromWebToken()

  • Uses @aws-sdk/client-sts
  • Available in browsers & native apps

The function fromWebToken returns AwsCredentialIdentityProvider that gets credentials calling STS AssumeRoleWithWebIdentity API

import { fromWebToken } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromWebToken } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  region,
  credentials: fromWebToken({
    // Required. ARN of the role that the caller is assuming.
    roleArn: "arn:aws:iam::1234567890:role/RoleA",
    // Required. The OAuth 2.0 access token or OpenID Connect ID token that is provided by the
    // identity provider.
    webIdentityToken: await openIdProvider(),
    // Optional. Custom STS client configurations overriding the default ones.
    clientConfig: { region },
    // Optional. A function that assumes a role with web identity and returns a promise fulfilled
    // with credentials for the assumed role.
    roleAssumerWithWebIdentity,
    // Optional. An identifier for the assumed role session.
    roleSessionName: "session_123",
    // Optional. The fully qualified host component of the domain name of the identity provider.
    providerId: "graph.facebook.com",
    // Optional. ARNs of the IAM managed policies that you want to use as managed session.
    policyArns: [{ arn: "arn:aws:iam::1234567890:policy/SomePolicy" }],
    // Optional. An IAM policy in JSON format that you want to use as an inline session policy.
    policy: "JSON_STRING",
    // Optional. The duration, in seconds, of the role session. Default to 3600.
    durationSeconds: 7200,
  }),
});

Examples

You can directly configure individual identity providers to access AWS resources using web identity federation. AWS currently supports authenticating users using web identity federation through several identity providers:

You must first register your application with the providers that your application supports. Next, create an IAM role and set up permissions for it. The IAM role you create is then used to grant the permissions you configured for it through the respective identity provider. For example, you can set up a role that allows users who logged in through Facebook to have read access to a specific Amazon S3 bucket you control.

After you have both an IAM role with configured privileges and an application registered with your chosen identity providers, you can set up the SDK to get credentials for the IAM role using helper code, as follows:

The value in the ProviderId parameter depends on the specified identity provider. The value in the WebIdentityToken parameter is the access token retrieved from a successful login with the identity provider. For more information on how to configure and retrieve access tokens for each identity provider, see the documentation for the identity provider.

fromContainerMetadata() and fromInstanceMetadata()

  • Not available in browsers & native apps

fromContainerMetadata and fromInstanceMetadata will create AwsCredentialIdentityProvider functions that read from the ECS container metadata service and the EC2 instance metadata service, respectively.

import { fromInstanceMetadata } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromInstanceMetadata } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromInstanceMetadata({
    // Optional. The connection timeout (in milliseconds) to apply to any remote requests.
    // If not specified, a default value of `1000` (one second) is used.
    timeout: 1000,
    // Optional. The maximum number of times any HTTP connections should be retried. If not
    // specified, a default value of `0` will be used.
    maxRetries: 0,
  }),
});
import { fromContainerMetadata } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromContainerMetadata } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromContainerMetadata({
    // Optional. The connection timeout (in milliseconds) to apply to any remote requests.
    // If not specified, a default value of `1000` (one second) is used.
    timeout: 1000,
    // Optional. The maximum number of times any HTTP connections should be retried. If not
    // specified, a default value of `0` will be used.
    maxRetries: 0,
  }),
});

A AwsCredentialIdentityProvider function created with fromContainerMetadata will return a promise that will resolve with credentials for the IAM role associated with containers in an Amazon ECS task. Please see IAM Roles for Tasks for more information on using IAM roles with Amazon ECS.

A AwsCredentialIdentityProvider function created with fromInstanceMetadata will return a promise that will resolve with credentials for the IAM role associated with an EC2 instance. Please see IAM Roles for Amazon EC2 for more information on using IAM roles with Amazon EC2. Both IMDSv1 (a request/response method) and IMDSv2 (a session-oriented method) are supported.

Please see Configure the instance metadata service for more information.

fromHttp()

  • Available in browsers & native apps, without the EC2 and Container metadata components.

This creates a provider function that makes a GET request to any provided HTTPS URL. A limited set of HTTP destinations are also accepted.

This is a general form of the fromContainerMetadata function.

The server is expected to respond with the following format in JSON:

type HttpProviderResponse = {
  AccessKeyId: string;
  SecretAccessKey: string;
  Token: string;
  AccountId?: string;
  Expiration: string; // rfc3339
};

The acceptable non-HTTPS destinations are described in the validation error if encountered:

URL not accepted. It must either be HTTPS or match one of the following:
  - loopback CIDR 127.0.0.0/8 or [::1/128]
  - ECS container host 169.254.170.2
  - EKS container host 169.254.170.23 or [fd00:ec2::23]

Node.js:

import { fromHttp } from "@aws-sdk/credential-providers";
// const { fromHttp } = require("@aws-sdk/credential-providers");

const client = new FooClient({
  credentials: fromHttp({
    /**
     * If this value is provided, it will be used as-is.
     */
    awsContainerCredentialsFullUri: "...",
    /**
     * If this value is provided instead of the full URI, it
     * will be appended to the default link local host of 169.254.170.2.
     */
    awsContainerCredentialsRelativeUri: "...",

    /**
     * Will be read on each credentials request to
     * add an Authorization request header value.
     */
    awsContainerAuthorizationTokenFile: "...",

    /**
     * An alternative to awsContainerAuthorizationTokenFile,
     * this is the token value itself.
     */
    awsContainerAuthorizationToken: "...",
  }),
});

If not provided in the JavaScript code, the following process envrionment variables will be read:

AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
AWS_CONTAINER_CREDENTIALS_FULL_URI
AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE
AWS_CONTAINER_AUTHORIZATION_TOKEN

Browsers:

import { fromHttp } from "@aws-sdk/credential-providers";

const client = new FooClient({
  credentials: fromHttp({
    /**
     * BROWSER ONLY.
     *
     * In browsers, a relative URI is not allowed, and a full URI must be provided.
     * HTTPS is required.
     *
     * This value is required for the browser environment.
     */
    credentialsFullUri: "...",

    /**
     * BROWSER ONLY.
     *
     * Providing this value will set an "Authorization" request
     * header value on the GET request.
     */
    authorizationToken: "...",
  }),
});

fromIni()

  • May use @aws-sdk/client-sso or @aws-sdk/client-sts depending on how the file is configured.
  • Not available in browsers & native apps.

fromIni creates AwsCredentialIdentityProvider functions that read from a shared credentials file at ~/.aws/credentials and a shared configuration file at ~/.aws/config. Both files are expected to be INI formatted with section names corresponding to profiles. Sections in the credentials file are treated as profile names, whereas profile sections in the config file must have the format of [profile profile-name], except for the default profile. Please see the sample files below for examples of well-formed configuration and credentials files.

Profiles that appear in both files will not be merged, and the version that appears in the credentials file will be given precedence over the profile found in the config file.

import { fromIni } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromIni } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromIni({
    // Optional. The configuration profile to use. If not specified, the provider will use the value
    // in the `AWS_PROFILE` environment variable or a default of `default`.
    profile: "profile",
    // Optional. The path to the shared credentials file. If not specified, the provider will use
    // the value in the `AWS_SHARED_CREDENTIALS_FILE` environment variable or a default of
    // `~/.aws/credentials`.
    filepath: "~/.aws/credentials",
    // Optional. The path to the shared config file. If not specified, the provider will use the
    // value in the `AWS_CONFIG_FILE` environment variable or a default of `~/.aws/config`.
    configFilepath: "~/.aws/config",
    // Optional. A function that returns a a promise fulfilled with an MFA token code for the
    // provided MFA Serial code. If a profile requires an MFA code and `mfaCodeProvider` is not a
    // valid function, the credential provider promise will be rejected.
    mfaCodeProvider: async (mfaSerial) => {
      return "token";
    },
    // Optional. Custom STS client configurations overriding the default ones.
    clientConfig: { region },
  }),
});

Sample files

~/.aws/credentials

[default]
aws_access_key_id=foo
aws_secret_access_key=bar

[dev]
aws_access_key_id=foo2
aws_secret_access_key=bar2

~/.aws/config

[default]
aws_access_key_id=foo
aws_secret_access_key=bar

[profile dev]
aws_access_key_id=foo2
aws_secret_access_key=bar2

profile with source profile

[second]
aws_access_key_id=foo
aws_secret_access_key=bar

[first]
source_profile=second
role_arn=arn:aws:iam::123456789012:role/example-role-arn

profile with source provider

You can supply credential_source options to tell the SDK where to source credentials for the call to AssumeRole. The supported credential providers are listed below:

[default]
role_arn=arn:aws:iam::123456789012:role/example-role-arn
credential_source = Ec2InstanceMetadata
[default]
role_arn=arn:aws:iam::123456789012:role/example-role-arn
credential_source = Environment
[default]
role_arn=arn:aws:iam::123456789012:role/example-role-arn
credential_source = EcsContainer

profile with web_identity_token_file

[default]
web_identity_token_file=/temp/token
role_arn=arn:aws:iam::123456789012:role/example-role-arn

You can specify another profile(second) whose credentials are used to assume the role by the role_arn setting in this profile(first).

[second]
web_identity_token_file=/temp/token
role_arn=arn:aws:iam::123456789012:role/example-role-2

[first]
source_profile=second
role_arn=arn:aws:iam::123456789012:role/example-role

profile with sso credentials

See fromSSO() for more information

fromEnv()

  • Not available in browser & native apps
import { fromEnv } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromEnv } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromEnv(),
});

fromEnv returns a AwsCredentialIdentityProvider function, that reads credentials from the following environment variables:

  • AWS_ACCESS_KEY_ID - The access key for your AWS account.
  • AWS_SECRET_ACCESS_KEY - The secret key for your AWS account.
  • AWS_SESSION_TOKEN - The session key for your AWS account. This is only needed when you are using temporary credentials.
  • AWS_CREDENTIAL_EXPIRATION - The expiration time of the credentials contained in the environment variables described above. This value must be in a format compatible with the ISO-8601 standard and is only needed when you are using temporary credentials.

If either the AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment variable is not set or contains a falsy value, the promise returned by the fromEnv function will be rejected.

fromProcess()

  • Not available in browsers & native apps
import { fromProcess } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromProcess } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromProcess({
    // Optional. The configuration profile to use. If not specified, the provider will use the value
    // in the `AWS_PROFILE` environment variable or a default of `default`.
    profile: "profile",
    // Optional. The path to the shared credentials file. If not specified, the provider will use
    // the value in the `AWS_SHARED_CREDENTIALS_FILE` environment variable or a default of
    // `~/.aws/credentials`.
    filepath: "~/.aws/credentials",
    // Optional. The path to the shared config file. If not specified, the provider will use the
    // value in the `AWS_CONFIG_FILE` environment variable or a default of `~/.aws/config`.
    configFilepath: "~/.aws/config",
  }),
});

fromSharedConfigFiles creates a AwsCredentialIdentityProvider functions that executes a given process and attempt to read its standard output to receive a JSON payload containing the credentials. The process command is read from a shared credentials file at ~/.aws/credentials and a shared configuration file at ~/.aws/config. Both files are expected to be INI formatted with section names corresponding to profiles. Sections in the credentials file are treated as profile names, whereas profile sections in the config file must have the format of[profile profile-name], except for the default profile. Please see the sample files below for examples of well-formed configuration and credentials files.

Profiles that appear in both files will not be merged, and the version that appears in the credentials file will be given precedence over the profile found in the config file.

Sample files

~/.aws/credentials

[default]
credential_process = /usr/local/bin/awscreds

[dev]
credential_process = /usr/local/bin/awscreds dev

~/.aws/config

[default]
credential_process = /usr/local/bin/awscreds

[profile dev]
credential_process = /usr/local/bin/awscreds dev

fromTokenFile()

  • Uses @aws-sdk/client-sts
  • Not available in browsers & native apps

The function fromTokenFile returns AwsCredentialIdentityProvider that reads credentials as follows:

  • Reads file location of where the OIDC token is stored from either provided option webIdentityTokenFile or environment variable AWS_WEB_IDENTITY_TOKEN_FILE.
  • Reads IAM role wanting to be assumed from either provided option roleArn or environment variable AWS_ROLE_ARN.
  • Reads optional role session name to be used to distinguish sessions from provided option roleSessionName or environment variable AWS_ROLE_SESSION_NAME. If session name is not defined, it comes up with a role session name.
  • Reads OIDC token from file on disk.
  • Calls sts:AssumeRoleWithWebIdentity via roleAssumerWithWebIdentity option to get credentials.
Configuration KeyEnvironment VariableRequiredDescription
webIdentityTokenFileAWS_WEB_IDENTITY_TOKEN_FILEtrueFile location of where the OIDC token is stored
roleArnAWS_ROLE_ARNtrueThe IAM role wanting to be assumed
roleSessionNameAWS_ROLE_SESSION_NAMEfalseThe IAM session name used to distinguish sessions
import { fromTokenFile } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromTokenFile } = require("@aws-sdk/credential-providers"); // CommonJS import

const client = new FooClient({
  credentials: fromTokenFile({
    // Optional. STS client config to make the assume role request.
    clientConfig: { region }
  });
});

fromSSO()

  • Uses @aws-sdk/client-sso & @aws-sdk/client-sso-oidc
  • Not available in browsers & native apps

This credential provider ONLY supports profiles using the SSO credential. If you have a profile that assumes a role which derived from the SSO credential, you should use the fromIni(), or @aws-sdk/credential-provider-node package.

fromSSO, that creates AwsCredentialIdentityProvider functions that read from the resolved access token from local disk then requests temporary AWS credentials. For guidance on the AWS Single Sign-On service, please refer to AWS's Single Sign-On documentation.

You can create the AwsCredentialIdentityProvider functions using the inline SSO parameters(ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName) or load them from AWS SDKs and Tools shared configuration and credentials files. Profiles in the credentials file are given precedence over profiles in the config file.

This credential provider is intended for use with the AWS SDK for Node.js.

Supported configuration

You may customize how credentials are resolved by providing an options hash to the fromSSO factory function. You can either load the SSO config from shared INI credential files, or specify the ssoStartUrl, ssoAccountId, ssoRegion, and ssoRoleName directly from the code.

import { fromSSO } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromSSO } = require("@aws-sdk/credential-providers") // CommonJS import

const client = new FooClient({
  credentials: fromSSO({
    // Optional. The configuration profile to use. If not specified, the provider will use the value
    // in the `AWS_PROFILE` environment variable or `default` by default.
    profile: "my-sso-profile",
    // Optional. The path to the shared credentials file. If not specified, the provider will use
    // the value in the `AWS_SHARED_CREDENTIALS_FILE` environment variable or a default of
    // `~/.aws/credentials`.
    filepath: "~/.aws/credentials",
    // Optional. The path to the shared config file. If not specified, the provider will use the
    // value in the `AWS_CONFIG_FILE` environment variable or a default of `~/.aws/config`.
    configFilepath: "~/.aws/config",
    // Optional. The URL to the AWS SSO service. Required if any of the `sso*` options(except for
    // `ssoClient`) is provided.
    ssoStartUrl: "https://d-abc123.awsapps.com/start",
    // Optional. The ID of the AWS account to use for temporary credentials. Required if any of the
    // `sso*` options(except for `ssoClient`) is provided.
    ssoAccountId: "1234567890",
    // Optional. The AWS region to use for temporary credentials. Required if any of the `sso*`
    // options(except for `ssoClient`) is provided.
    ssoRegion: "us-east-1",
    // Optional. The name of the AWS role to assume. Required if any of the `sso*` options(except
    // for `ssoClient`) is provided.
    ssoRoleName: "SampleRole",
    // Optional. Overwrite the configuration used construct the SSO service client. If not
    // specified, a default SSO client will be created with the region specified in the profile
    // `sso_region` entry.
    clientConfig: { region },
  }),
});

SSO Login with the AWS CLI

This credential provider relies on the AWS CLI to log into an AWS SSO session. Here's a brief walk-through:

  1. Create a new AWS SSO enabled profile using the AWS CLI. It will ask you to login to your AWS SSO account and prompt for the name of the profile:
$ aws configure sso
...
...
CLI profile name [123456789011_ReadOnly]: my-sso-profile<ENTER>
  1. Configure your SDK client with the SSO credential provider:
//...
const client = new FooClient({ credentials: fromSSO({ profile: "my-sso-profile" }) });

Alternatively, the SSO credential provider is supported in shared INI credentials provider

//...
const client = new FooClient({ credentials: fromIni({ profile: "my-sso-profile" }) });
  1. To log out from the current SSO session, use the AWS CLI:
$ aws sso logout
Successfully signed out of all SSO profiles.

Sample files

This credential provider is only applicable if the profile specified in shared configuration and credentials files contain ALL of the following entries.

~/.aws/credentials

[sample-profile]
sso_account_id = 012345678901
sso_region = us-east-1
sso_role_name = SampleRole
sso_start_url = https://d-abc123.awsapps.com/start

~/.aws/config

[profile sample-profile]
sso_account_id = 012345678901
sso_region = us-east-1
sso_role_name = SampleRole
sso_start_url = https://d-abc123.awsapps.com/start

fromNodeProviderChain()

  • May use @aws-sdk/client-sts, @aws-sdk/client-sso, etc. depending on which link in the chain finally resolves credentials.
  • Not available in browsers & native apps

The credential provider used as default in the Node.js clients, but with default role assumers so you don't need to import them from STS client and supply them manually. You normally don't need to use this explicitly in the client constructor. It is useful for utility functions requiring credentials like S3 presigner, or RDS signer.

This credential provider will attempt to find credentials from the following sources (listed in order of precedence):

This credential provider will invoke one provider at a time and only continue to the next if no credentials have been located. For example, if the process finds values defined via the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, the files at ~/.aws/credentials and ~/.aws/config will not be read, nor will any messages be sent to the Instance Metadata Service

import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; // ES6 import
// const { fromNodeProviderChain } = require("@aws-sdk/credential-providers") // CommonJS import
const credentialProvider = fromNodeProviderChain({
  //...any input of fromEnv(), fromSSO(), fromTokenFile(), fromIni(),
  // fromProcess(), fromInstanceMetadata(), fromContainerMetadata()
  // Optional. Custom STS client configurations overriding the default ones.
  clientConfig: { region },
});

createCredentialChain()

You can use this helper to create a credential chain of your own.

A credential chain is created from a list of functions of the signature () => Promise[AwsCredentialIdentity](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-smithy-types/Interface/AwsCredentialIdentity/), composed together such that the overall chain has the same signature.

That is why you can provide the chained credential provider to the same field (credentials) as any single provider function.

All the providers from this package are compatible, and can be used to create such a chain.

As with any function provided to the credentials SDK client constructor configuration field, if the credential object returned does not contain an expiration (type Date), the client will only ever call the provider function once. You do not need to memoize this function.

To enable automatic refresh, the credential provider function should set an expiration (Date) field. When this expiration approaches within 5 minutes, the provider function will be called again by the client in the course of making SDK requests.

To assist with this, the createCredentialChain has a chainable helper .expireAfter(milliseconds: number). An example is included below.

import { fromEnv, fromIni, createCredentialChain } from "@aws-sdk/credential-providers";
import { S3 } from "@aws-sdk/client-s3";

// You can mix existing AWS SDK credential providers
// and custom async functions returning credential objects.
new S3({
  credentials: createCredentialChain(
    fromEnv(),
    async () => {
      // credentials customized by your code...
      return credentials;
    },
    fromIni()
  ),
});

// Set a max duration on the credentials (client side only).
// A set expiration will cause the credentials function to be called again
// when the time left is less than 5 minutes.
new S3({
  // This setting indicates expiry after 15 minutes (in milliseconds) with `15 * 60_000`.
  // Due to the 5 minute expiry window, the function will be called approximately every
  // 10 minutes under continuous usage of this client.
  credentials: createCredentialChain(fromEnv(), fromIni()).expireAfter(15 * 60_000),
});

// Apply shared init properties.
const init = { logger: console };

new S3({
  credentials: createCredentialChain(fromEnv(init), fromIni(init)),
});

Add Custom Headers to STS assume-role calls

You can specify the plugins--groups of middleware, to inject to the STS client. For example, you can inject custom headers to each STS assume-role calls. It's available in fromTemporaryCredentials(), fromWebToken(), fromTokenFile(), fromIni().

Code example:

const addConfusedDeputyMiddleware = (next) => (args) => {
  args.request.headers["x-amz-source-account"] = account;
  args.request.headers["x-amz-source-arn"] = sourceArn;
  return next(args);
};
const confusedDeputyPlugin = {
  applyToStack: (stack) => {
    stack.add(addConfusedDeputyMiddleware, { step: "finalizeRequest" });
  },
};
const provider = fromTemporaryCredentials({
  // Required. Options passed to STS AssumeRole operation.
  params: {
    RoleArn: "arn:aws:iam::1234567890:role/Role",
  },
  clientPlugins: [confusedDeputyPlugin],
});
@candle-face/shared-lambda@vastly/wave-cli@recognition-game/shared-aws@recognition-game/shared-backend@candle-face/shared-aws@elemental-clouds/carbon@elemental-clouds/osmiumbrianfoody-aws-utilsrogerfelipensk-dynamo-v3publish-cdk-assets@infinitebrahmanuniverse/nolb-_aws-sdamazon-connect-utilsrenovate@everything-registry/sub-chunk-102@bongkow/aws-clientsevery-utilspt-crystal-olive@aws-deploy-plugins/lambdatakomotencloud-js-sdkwiddixwhatwhywhenandwho-goodiesvwbl-sdkvwbl-corevwbl-core-testweddinglanka_main_backendws-cdk-deployers3presignedurl_v3s3shserverless-spyserverless-domain-managerserverless-dynamodb-stream-arn-plugin-2serverless-vpc-discoverysampicsecretformsecretsmanager-versioningvm-x-aivite-plugin-aws3vpc-describe@friendfetcher/api-hono@likeminds.community/likeminds-feed-reactjsmerloc-climerloc-locallincd-s3likeminds-feed-reactjs-betallm-exelolajsii-releaseinsomnia-plugin-aws-iam-v4insomnia-plugin-aws-profile-authleo-connector-elasticsearchhumidity-clikeypalambda-live-debuggerlakefsnearfsmy-test-jewellsctlnode-vault-clientotter-video-clipublibpipeline-project-toolplayshotobsidian-to-notionnx-awsprerender-aws-s3-cache-rodcope1nestjs-aws-configqllm-libstrapi-provider-s3-bucket-uploadrws-js-serverrotate-aws-keyrotate-keyslsberry-testerulostypescript-upload-docstoxeus-node-sdk@anthropic-ai/bedrock-sdk@artilleryio/platform-fargate@ampt/cloud@andreafspeziale/os-cli@atls/nestjs-s3-client@ailly/core@allure-ai/abs-sdk@allure-ai/sdk@aws-cdk-testing/cli-integ@aws-amplify/sandbox@aws-amplify/model-generator@backstage/integration-aws-node@backstage/plugin-techdocs-node@backstage/plugin-catalog-backend-module-aws@backstage/plugin-kubernetes-backend@aws-sdk/rds-signer@awsu/cli@awsu/core@aws/neptune-for-graphql@aws/sbt-point-solutions-lib@awsless/awsless@awsless/formation@awsless/open-search@aws/agents-for-amazon-bedrock-blueprints
3.685.0

21 days ago

3.682.0

24 days ago

3.678.0

30 days ago

3.679.0

29 days ago

3.677.0

1 month ago

3.675.0

1 month ago

3.664.0

2 months ago

3.670.0

1 month ago

3.666.0

2 months ago

3.665.0

2 months ago

3.669.0

1 month ago

3.668.0

1 month ago

3.667.0

1 month ago

3.662.0

2 months ago

3.658.1

2 months ago

3.658.0

2 months ago

3.649.0

2 months ago

3.654.0

2 months ago

3.645.0

3 months ago

3.651.1

2 months ago

3.650.0

2 months ago

3.630.0

3 months ago

3.592.0

6 months ago

3.588.0

6 months ago

3.637.0

3 months ago

3.614.0

4 months ago

3.632.0

3 months ago

3.606.0

5 months ago

3.629.0

3 months ago

3.620.0

4 months ago

3.583.0

6 months ago

3.620.1

4 months ago

3.617.0

4 months ago

3.631.0

3 months ago

3.582.0

6 months ago

3.616.0

4 months ago

3.622.0

4 months ago

3.596.0

5 months ago

3.621.0

4 months ago

3.613.0

5 months ago

3.587.0

6 months ago

3.624.0

4 months ago

3.598.0

5 months ago

3.635.0

3 months ago

3.590.0

6 months ago

3.609.0

5 months ago

3.623.0

4 months ago

3.600.0

5 months ago

3.577.0

6 months ago

3.576.0

6 months ago

3.575.0

6 months ago

3.574.0

7 months ago

3.572.0

7 months ago

3.568.0

7 months ago

3.567.0

7 months ago

3.569.0

7 months ago

3.565.0

7 months ago

3.564.0

7 months ago

3.563.0

7 months ago

3.556.0

7 months ago

3.554.0

7 months ago

3.552.0

8 months ago

3.549.0

8 months ago

3.540.0

8 months ago

3.535.0

8 months ago

3.533.0

8 months ago

3.529.1

9 months ago

3.529.0

9 months ago

3.525.0

9 months ago

3.523.0

9 months ago

3.521.0

9 months ago

3.515.0

9 months ago

3.514.0

9 months ago

3.513.0

9 months ago

3.511.0

10 months ago

3.509.0

10 months ago

3.507.0

10 months ago

3.504.1

10 months ago

3.504.0

10 months ago

3.503.0

10 months ago

3.502.0

10 months ago

3.503.1

10 months ago

3.501.0

10 months ago

3.499.0

10 months ago

3.498.0

10 months ago

3.496.0

10 months ago

3.495.0

10 months ago

3.490.0

11 months ago

3.489.0

11 months ago

3.485.0

11 months ago

3.484.0

11 months ago

3.481.0

11 months ago

3.478.0

11 months ago

3.477.0

11 months ago

3.476.0

11 months ago

3.474.0

11 months ago

3.473.0

11 months ago

3.470.0

12 months ago

3.468.0

12 months ago

3.460.0

12 months ago

3.462.0

12 months ago

3.461.0

12 months ago

3.458.0

12 months ago

3.465.0

12 months ago

3.445.0

1 year ago

3.444.0

1 year ago

3.451.0

1 year ago

3.450.0

1 year ago

3.449.0

1 year ago

3.454.0

1 year ago

3.436.0

1 year ago

3.435.0

1 year ago

3.438.0

1 year ago

3.441.0

1 year ago

3.437.0

1 year ago

3.385.0

1 year ago

3.362.0

1 year ago

3.422.1

1 year ago

3.422.0

1 year ago

3.397.0

1 year ago

3.408.0

1 year ago

3.369.0

1 year ago

3.418.0

1 year ago

3.421.0

1 year ago

3.433.0

1 year ago

3.410.0

1 year ago

3.387.0

1 year ago

3.391.0

1 year ago

3.413.0

1 year ago

3.386.0

1 year ago

3.363.0

1 year ago

3.423.0

1 year ago

3.398.0

1 year ago

3.409.0

1 year ago

3.389.0

1 year ago

3.378.0

1 year ago

3.370.0

1 year ago

3.427.0

1 year ago

3.430.0

1 year ago

3.388.0

1 year ago

3.425.0

1 year ago

3.377.0

1 year ago

3.414.0

1 year ago

3.429.0

1 year ago

3.395.0

1 year ago

3.382.0

1 year ago

3.379.1

1 year ago

3.428.0

1 year ago

3.405.0

1 year ago

3.431.0

1 year ago

3.347.0

1 year ago

3.347.1

1 year ago

3.359.0

1 year ago

3.351.0

1 year ago

3.358.0

1 year ago

3.350.0

1 year ago

3.353.0

1 year ago

3.348.0

1 year ago

3.352.0

1 year ago

3.342.0

1 year ago

3.354.0

1 year ago

3.345.0

1 year ago

3.360.0

1 year ago

3.357.0

1 year ago

3.344.0

1 year ago

3.332.0

2 years ago

3.329.0

2 years ago

3.327.0

2 years ago

3.335.0

2 years ago

3.316.0

2 years ago

3.312.0

2 years ago

3.328.0

2 years ago

3.326.0

2 years ago

3.341.0

1 year ago

3.319.0

2 years ago

3.338.0

2 years ago

3.315.0

2 years ago

3.325.0

2 years ago

3.321.1

2 years ago

3.337.0

2 years ago

3.306.0

2 years ago

3.309.0

2 years ago

3.310.0

2 years ago

3.301.0

2 years ago

3.294.0

2 years ago

3.279.0

2 years ago

3.290.0

2 years ago

3.271.0

2 years ago

3.298.0

2 years ago

3.267.0

2 years ago

3.282.0

2 years ago

3.300.0

2 years ago

3.276.0

2 years ago

3.295.0

2 years ago

3.291.0

2 years ago

3.272.0

2 years ago

3.299.0

2 years ago

3.287.0

2 years ago

3.303.0

2 years ago

3.296.0

2 years ago

3.292.0

2 years ago

3.288.0

2 years ago

3.297.0

2 years ago

3.278.0

2 years ago

3.293.0

2 years ago

3.266.0

2 years ago

3.289.0

2 years ago

3.266.1

2 years ago

3.281.0

2 years ago

3.256.0

2 years ago

3.252.0

2 years ago

3.263.0

2 years ago

3.257.0

2 years ago

3.245.0

2 years ago

3.241.0

2 years ago

3.264.0

2 years ago

3.254.0

2 years ago

3.258.0

2 years ago

3.261.0

2 years ago

3.259.0

2 years ago

3.262.0

2 years ago

3.196.0

2 years ago

3.192.0

2 years ago

3.210.0

2 years ago

3.218.0

2 years ago

3.188.0

2 years ago

3.202.0

2 years ago

3.197.0

2 years ago

3.193.0

2 years ago

3.208.0

2 years ago

3.234.0

2 years ago

3.211.0

2 years ago

3.238.0

2 years ago

3.215.0

2 years ago

3.222.0

2 years ago

3.226.0

2 years ago

3.198.0

2 years ago

3.194.0

2 years ago

3.209.0

2 years ago

3.235.0

2 years ago

3.212.0

2 years ago

3.216.0

2 years ago

3.190.0

2 years ago

3.231.0

2 years ago

3.223.0

2 years ago

3.204.0

2 years ago

3.200.0

2 years ago

3.195.0

2 years ago

3.229.0

2 years ago

3.199.0

2 years ago

3.213.0

2 years ago

3.236.0

2 years ago

3.224.0

2 years ago

3.201.0

2 years ago

3.179.0

2 years ago

3.186.0

2 years ago

3.180.0

2 years ago

3.185.0

2 years ago

3.183.0

2 years ago

3.181.0

2 years ago

3.154.0

2 years ago

3.150.0

2 years ago

3.171.0

2 years ago

3.165.0

2 years ago

3.163.0

2 years ago

3.161.0

2 years ago

3.169.0

2 years ago

3.170.0

2 years ago

3.159.0

2 years ago

3.157.0

2 years ago

3.178.0

2 years ago

3.162.0

2 years ago

3.160.0

2 years ago

3.168.0

2 years ago

3.112.0

2 years ago

3.137.0

2 years ago

3.118.0

2 years ago

3.131.0

2 years ago

3.110.0

2 years ago

3.109.0

2 years ago

3.100.0

2 years ago

3.127.0

2 years ago

3.142.0

2 years ago

3.121.0

2 years ago

3.118.1

2 years ago

3.130.0

2 years ago

3.145.0

2 years ago

3.107.0

2 years ago

3.128.0

2 years ago

3.105.0

2 years ago

3.99.0

2 years ago

3.141.0

2 years ago

3.81.0

3 years ago

3.87.0

3 years ago

3.85.0

3 years ago

3.92.0

3 years ago

3.79.0

3 years ago

3.94.0

3 years ago

3.82.0

3 years ago

3.80.0

3 years ago

3.78.0

3 years ago

3.95.0

3 years ago

3.67.0

3 years ago

3.58.0

3 years ago

3.56.0

3 years ago

3.76.0

3 years ago

3.55.0

3 years ago

3.54.1

3 years ago

3.54.0

3 years ago

3.74.0

3 years ago

3.75.0

3 years ago

3.72.0

3 years ago

3.53.0

3 years ago

3.45.0

3 years ago

3.46.0

3 years ago

3.52.0

3 years ago

3.51.0

3 years ago

3.50.0

3 years ago

3.47.0

3 years ago

3.48.0

3 years ago

3.47.1

3 years ago

3.49.0

3 years ago

3.47.2

3 years ago

3.41.0

3 years ago

3.42.0

3 years ago

3.43.0

3 years ago

3.40.0

3 years ago

3.39.0

3 years ago

3.38.0

3 years ago

3.35.0

3 years ago

3.36.0

3 years ago

3.37.0

3 years ago

3.36.1

3 years ago

3.34.0

3 years ago

3.33.0

3 years ago

3.32.0

3 years ago

3.31.0

3 years ago

3.30.0

3 years ago

3.29.0

3 years ago

3.28.0

3 years ago

3.27.0

3 years ago