# @aws-sdk/credential-providers

[![NPM version](https://img.shields.io/npm/v/@aws-sdk/credential-providers/latest.svg)](https://www.npmjs.com/package/@aws-sdk/credential-providers)
[![NPM downloads](https://img.shields.io/npm/dm/@aws-sdk/credential-providers.svg)](https://www.npmjs.com/package/@aws-sdk/credential-providers)

A collection of all credential providers.

# Table of Contents

- [Terminology](#terminology)
  - [Credentials Provider](#credentials-provider)
  - [Outer and inner clients](#outer-and-inner-clients)
- [Resolving AWS Region in credential providers (e.g. STS region)](#resolving-aws-region-in-credential-providers-eg-sts-region)
- [From Cognito Identity](#fromcognitoidentity)
- [From Cognito Identity Pool](#fromcognitoidentitypool)
- [From Temporary Credentials](#fromtemporarycredentials)
- [From Web Token](#fromwebtoken)
  - [Examples](#examples)
- [From Token File](#fromtokenfile)
- [From Instance and Container Metadata Service](#fromcontainermetadata-and-frominstancemetadata)
- [From HTTP(S)](#fromhttp)
- [From Shared INI files](#fromini)
  - [Sample Files](#sample-files)
- [From Environmental Variables](#fromenv)
- [From Credential Process](#fromprocess)
  - [Sample files](#sample-files-1)
- [From Single Sign-On Service](#fromsso)
  - [Supported Configuration](#supported-configuration)
  - [SSO login with AWS CLI](#sso-login-with-the-aws-cli)
  - [Sample Files](#sample-files-2)
- [From Login Credentials](#fromLoginCredentials)
  - [Login with AWS CLI](#login-with-aws-cli)
  - [Sample Files](#sample-files-3)
- [From Node.js default credentials provider chain](#fromnodeproviderchain)
- [Creating a custom credentials chain](#createcredentialchain)

## Terminology

#### Credentials Provider

An `AwsCredentialIdentityProvider` is any function that matches the signature:

```ts
() =>
  Promise<{
    /**
     * AWS access key ID
     */
    readonly accessKeyId: string;
    /**
     * AWS secret access key
     */
    readonly secretAccessKey: string;
    /**
     * A security or session token to use with these credentials. Usually
     * present for temporary credentials.
     */
    readonly sessionToken?: string;
    /**
     * A `Date` when the identity or credential will no longer be accepted.
     * You can set or override this on the client side to force a refresh
     * call of the function supplying the credentials when 5 minutes remain.
     */
    readonly expiration?: Date;
  }>;
```

That is, an async function which returns an object containing AWS credentials.

Whether you write your own such function or use one of the providers from this package, when used in
conjunction with an AWS SDK Client, the client will cache the resulting credentials
until there is less than 5 minutes remaining to their expiration, at which point the
function will be called again, and the new credentials cached.

This is designed to minimize the number of credential requests. Each client
instance has a separate cache of credentials, so if you want to share credential caching
between clients, you'll need to implement your own cache outside the SDK.

#### Outer and inner clients

A "parent/outer/upper/caller" (position), or "data" (purpose) client refers
to a client being initialized explicitly by the SDK user.

An "inner" (position), or "credentials" (purpose) client
refers to a client being initialized by the SDK in the course
of retrieving credentials. Several AWS SDK credentials providers
make use of inner clients such as Cognito, SSO, STS, and SSO-OIDC.

```ts
// Example: outer client and inner client
const s3 = new S3Client({
  credentials: fromIni(),
});
```

In the above example, `S3Client` is the outer client, and
if the `fromIni` credentials provider uses STS::AssumeRole, the
`STSClient` initialized by the SDK is the inner client.

## Resolving AWS Region in credential providers (e.g. STS region)

When a credential provider uses an SDK client to retrieve credentials, commonly STS, the
control of the STS region follows this logic:

```js
import { fromIni } from "@aws-sdk/credential-providers";

/*
# AWS config file contents
[profile default]
region = profile-region
role_arn = ROLE_ARN
source_profile = assume

[profile assume]
...
 */

process.env.AWS_REGION = "env-region";

const provider = fromIni({
  clientConfig: {
    region: "credential-provider-config-region",
  },
});

const client = new SDKClient({
  region: "context-client-region",
  credentials: provider,
});

const fallbackRegion = "us-east-1";
```

As shown above, there are many sources of region information. The priority order is:

1. `credential-provider-config-region` - given in code to the credential provider itself.
2. `profile-region` **\*** - if credential provider is resolving credentials from the config file, the config file's
   region takes precedence in this case over AWS_REGION env.
3. `context-client-region` - the region resolved by an SDK client using the credential provider.
4. `env-region` - AWS_REGION environment variable.
5. `profile-region` **\*** - if credential provider is not resolving credentials from the config file, the config file's
   region is lower priority than AWS_REGION env.
6. `us-east-1` (fallback) - this is a legacy fallback value. It's more likely that the client will fail to execute any
   operation if none of the other region sources were set.

This differs from _direct_ instantiation of the STSClient, which follows this order, which is the same for all clients:

```js
import { STSClient } from "@aws-sdk/client-sts";
/*
# AWS config file contents
[profile default]
region = profile-region
 */

process.env.AWS_REGION = "env-region";

const client = new STSClient({
  region: "client-region",
});
```

1. `client-region`
2. `env-region`
3. `profile-region` (config file)
4. thrown error (no us-east-1 fallback)

# Credential providers

## `fromCognitoIdentity()`

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

The function `fromCognitoIdentity()` returns a credentials provider that retrieves credentials for
the provided identity ID. See [GetCredentialsForIdentity API][getcredentialsforidentity_api]
for more information.

```javascript
import { fromCognitoIdentity } from "@aws-sdk/credential-providers"; // ES6 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 overrides. This is passed to an inner Cognito client
    // instantiated to resolve the credentials. Region and profile
    // are inherited from the upper client if present unless overridden.
    clientConfig: {},
  }),
});
```

## `fromCognitoIdentityPool()`

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

The function `fromCognitoIdentityPool()` returns `AwsCredentialIdentityProvider` that calls [GetId API][getid_api]
to obtain an `identityId`, then generates temporary AWS credentials with
[GetCredentialsForIdentity API][getcredentialsforidentity_api], see
[`fromCognitoIdentity()`](#fromcognitoidentity).

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

```javascript
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; // ES6 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 overrides. This is passed to an inner Cognito client
    // instantiated to resolve the credentials. Region and profile
    // are inherited from the upper client if present unless overridden.
    clientConfig: {},
  }),
});
```

## `fromTemporaryCredentials()`

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

The function `fromTemporaryCredentials` returns `AwsCredentialIdentityProvider` that retrieves temporary
credentials from [STS AssumeRole API][assumerole_api].

```javascript
import { fromTemporaryCredentials } from "@aws-sdk/credential-providers"; // ES6 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. 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";
    },
    // Optional overrides. This is passed to an inner STS client instantiated to
    // resolve the credentials. Region and profile
    // are inherited from the upper client if present unless overridden.
    clientConfig: {},
  }),
});
```

## `fromWebToken()`

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

The function `fromWebToken` returns an `AwsCredentialIdentityProvider` that gets credentials calling
[STS AssumeRoleWithWebIdentity API][assumerolewithwebidentity_api]

```javascript
import { fromWebToken } from "@aws-sdk/credential-providers"; // ES6 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. 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 3600.
    durationSeconds: 7200,
    // Optional overrides. This is passed to an inner STS client
    // instantiated to resolve the credentials. Region and profile
    // are inherited from the upper client if present unless overridden.
    clientConfig: {},
  }),
});
```

### 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:

- [Login with Amazon](https://login.amazon.com/)

- [Facebook Login](https://developers.facebook.com/docs/facebook-login/web/)

- [Google Sign-in](https://developers.google.com/identity/)

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.

```javascript
import { fromInstanceMetadata } from "@aws-sdk/credential-providers"; // ES6 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,
  }),
});
```

```javascript
import { fromContainerMetadata } from "@aws-sdk/credential-providers"; // ES6 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,
  }),
});
```

An `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][iam_roles_for_tasks] for more information on using IAM roles with Amazon
ECS.

An `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][iam_roles_for_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][config_instance_metadata] 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:

```ts
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:

```js
import { fromHttp } from "@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:

```js
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 an `AwsCredentialIdentityProvider` function that reads 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](#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.

```javascript
import { fromIni } from "@aws-sdk/credential-providers"; // ES6 import

const client = new FooClient({
  // As of v3.714.0, an easy way to select a profile is to set it on the client.
  // This will read both client configuration and credentials instructions
  // from that profile. The order of priority is:
  // 1. this field (only applies to this client).
  // 2. AWS_PROFILE environment variable (affects all clients).
  // 3. the default profile.
  profile: "my-profile",

  // Please note that the data client's region
  // will not be used by STS requests originating from the `fromIni`
  // provider if the profile(s) used have their own configured regions.
  // If the profile(s) have no regions set, then the data client's
  // region will be the fallback for the inner STS client.
  // For SSO via `fromIni`, the `sso_region` value will be used, since it is required.
  region: "us-west-2",

  credentials: fromIni({
    // Optional. Defaults to the client's profile if that is set.
    // You can specify a profile here as well, but this applies
    // only to the credential resolution and not to the upper client.
    // Use this instead of the client profile if you need a separate profile
    // for credentials.
    profile: "my-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 overrides. This is passed to an inner STS or SSO client
    // instantiated to resolve the credentials. Region and profile
    // are inherited from the upper client if present unless overridden, so
    // it should not be necessary to set those.
    //
    // Warning: setting a region here overrides the region set in the config file
    // for the selected profile.
    clientConfig: {},
  }),
});
```

### Sample files

#### `~/.aws/credentials`

```ini
[default]
aws_access_key_id=foo
aws_secret_access_key=bar

[dev]
aws_access_key_id=foo2
aws_secret_access_key=bar2
```

#### `~/.aws/config`

```ini
[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

```ini
[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:

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

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

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

#### profile with web_identity_token_file

```ini
[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`).

```ini
[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()`](#fromsso) for more information

## `fromEnv()`

- Not available in browser & native apps

```javascript
import { fromEnv } from "@aws-sdk/credential-providers"; // ES6 import

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

`fromEnv` returns an `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][iso8601_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

```javascript
import { fromProcess } from "@aws-sdk/credential-providers"; // ES6 import

const client = new FooClient({
  // Optional, available on clients as of v3.714.0.
  profile: "my-profile",
  credentials: fromProcess({
    // Optional. Defaults to the client's profile if that is set.
    // You can specify a profile here as well, but this applies
    // only to the credential resolution and not to the upper client.
    // Use this instead of the client profile if you need a separate profile
    // for credentials.
    profile: "my-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",
  }),
});
```

`fromProcess` creates an `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](#sample-files-1) 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`

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

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

#### `~/.aws/config`

```ini
[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 Key** | **Environment Variable**    | **Required** | **Description**                                   |
| --------------------- | --------------------------- | ------------ | ------------------------------------------------- |
| webIdentityTokenFile  | AWS_WEB_IDENTITY_TOKEN_FILE | true         | File location of where the `OIDC` token is stored |
| roleArn               | AWS_ROLE_ARN                | true         | The IAM role wanting to be assumed                |
| roleSessionName       | AWS_ROLE_SESSION_NAME       | false        | The IAM session name used to distinguish sessions |

```javascript
import { fromTokenFile } from "@aws-sdk/credential-providers"; // ES6 import

const client = new FooClient({
  region: "us-west-2",
  credentials: fromTokenFile({
    // Optional overrides. This is passed to an inner STS client
    // instantiated to resolve the credentials. Region is inherited
    // from the upper client if present unless overridden.
    clientConfig: {},
  }),
});
```

## `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()`](#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][sso_api].

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][shared_config_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.

```javascript
import { fromSSO } from "@aws-sdk/credential-providers"; // ES6 import

const client = new FooClient({
  // Optional, available on clients as of v3.714.0.
  profile: "my-sso-profile",
  credentials: fromSSO({
    // Optional. Defaults to the client's profile if that is set.
    // You can specify a profile here as well, but this applies
    // only to the credential resolution and not to the upper client.
    // Use this instead of the client profile if you need a separate profile
    // for credentials.
    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][cli_sso] 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:

```console
$ aws configure sso
...
...
CLI profile name [123456789011_ReadOnly]: my-sso-profile<ENTER>
```

2. Configure your SDK client with the SSO credential provider:

```javascript
//...
const client = new FooClient({ credentials: fromSSO({ profile: "my-sso-profile" }) });
```

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

```javascript
//...
const client = new FooClient({ credentials: fromIni({ profile: "my-sso-profile" }) });
```

3. To log out from the current SSO session, use the AWS CLI:

```console
$ 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`

```ini
[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`

```ini
[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
```

## `fromLoginCredentials()`

- Uses `@aws-sdk/client-signin`
- Not available in browsers & native apps

`fromLoginCredentials` creates an `AwsCredentialIdentityProvider` function that reads from cached login credentials stored on disk after authenticating with the AWS CLI using the `aws login` command. The provider automatically refreshes when the credentials are about to expire.

This provider is not typically used in an explicit fashion and is designed to simplify credential usage by allowing SDK clients to work seamlessly after running `aws login` with AWS CLI, without requiring any additional configuration.

```javascript
import { fromLoginCredentials } from "@aws-sdk/credential-providers"; // ES6 import

const client = new FooClient({
  // Optional, available on clients as of v3.714.0.
  profile: "my-profile",
  credentials: fromLoginCredentials({
    // Optional. Defaults to the client's profile if that is set.
    // Should match the profile name used with 'aws login --profile <name>'
    // to ensure credentials are found in the cache. Uses 'default' if no
    // --profile was specified during aws login or if this option is omitted.
    profile: "my-profile",
    // Optional. Overwrite the configuration used to construct the signin service client.
    // If not specified, a default signin client will be created with the region specified in the profile.
    // Warning: setting a region here overrides the region set in the config file
    // for the selected profile.
    clientConfig: { region },
  }),
});
```

### Login with AWS CLI

This credential provider relies on the AWS CLI to authenticate and cache login credentials. Here's how to set it up:

1. **Initial Login**: Run the `aws login` command to authenticate using your existing AWS Management Console credentials:

```console
$ aws login
```

2. **Named Profile**: To sign in to a named profile or create a new one, use the `--profile` option:

```console
$ aws login --profile my-dev-profile
```

3. **Region Configuration**: If this is a new profile or no AWS Region has been specified, the AWS CLI prompts you to provide a region:

```console
No AWS region has been configured. The AWS region is the geographic location of
your AWS resources.

If you've used AWS before and already have resources in your account, tell us
which region they were created in. If you haven't created resources in your account
before, you can pick the region closest to you:
https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html.
You are able to change the region in the CLI at any time with the command
`aws configure set region NEW_REGION`.

AWS Region [us-east-1]:
```

4. **Browser Authentication**: The AWS CLI attempts to open your default browser for the sign in process:

```console
Attempting to open the login page for `us-east-1` in your default browser.
If the browser does not open, use the following URL to complete your login:
https://signin.us-east-1.amazonaws.com/authorize?<abbreviated>
```

5. **No Browser Option**: If the device using the AWS CLI does not have a browser, you can use the `--no-browser` option:

```console
$ aws login --no-browser
```

This will provide a URL for you to open on a browser-enabled device and prompt for an authorization code.

6. **Logout**: When you are done using your session, you can let your credentials expire, or run the `aws logout` command:

```console
$ aws logout
$ aws logout --profile my-dev-profile
```

### Cached Credentials

The temporary cached credentials, as well as the metadata required to refresh them are stored by default in `~/.aws/login/cache` on Linux and macOS, or `%USERPROFILE%\.aws\login\cache` on Windows.

You can override this location by setting the `AWS_LOGIN_CACHE_DIRECTORY` environment variable.

### Sample Files

After running `aws login`, the configuration file will contain a `login_session` entry:

#### `~/.aws/config`

```ini
[default]
login_session = arn:aws:iam::0123456789012:user/username
region = us-east-1
```

## `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):

- [Environment variables exposed via `process.env`](#fromenv)
- [SSO credentials from token cache](#fromsso)
- [Web identity token credentials](#fromtokenfile)
- [Shared credentials and config ini files](#fromini)
- [The EC2/ECS Instance Metadata Service](#fromcontainermetadata-and-frominstancemetadata)

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

```js
import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; // ES6 import

const credentialProvider = fromNodeProviderChain({
  // This provider accepts any input of fromEnv(), fromSSO(), fromTokenFile(),
  // fromIni(), fromProcess(), fromInstanceMetadata(), fromContainerMetadata()
  // that exist in the default credential chain.

  // Optional client overrides. This is passed to an inner credentials client
  // that may be STS, SSO, or other instantiated to resolve the credentials.
  // Region and profile are inherited from the upper client if present
  // unless overridden, so it should not be necessary to set those.
  //
  // Warning: setting a region here may override the region set in
  // the config file for the selected profile if profile-based
  // credentials are used.
  clientConfig: {},
});
```

## `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.

```ts
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)),
});
```

[getcredentialsforidentity_api]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html
[getid_api]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html
[assumerole_api]: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
[assumerolewithwebidentity_api]: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html
[iam_roles_for_tasks]: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
[iam_roles_for_ec2]: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
[config_instance_metadata]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
[iso8601_standard]: https://en.wikipedia.org/wiki/ISO_8601
[sso_api]: https://aws.amazon.com/single-sign-on/
[shared_config_files]: https://docs.aws.amazon.com/credref/latest/refdocs/creds-config-files.html
[cli_sso]: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html#sso-configure-profile
