

# Using credentials providers in the AWS SDK for Java 2.x
<a name="credentials"></a>

The role of a credentials provider in the AWS SDK for Java 2.x is to source and supply credentials to the SDK's AWS service clients. The SDK uses the credentials it sources to authenticate with the service by cryptographically signing each request. Credentials usually consist of access keys—an access key ID and a secret access key together. 

When you use temporary credentials, which are used when you setup [SSO token provider configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#sso-token-config) or configure your runtime to [assume an IAM (AWS Identity and Access Management) role](https://docs.aws.amazon.com/sdkref/latest/guide/access-assume-role.html#credOrSourceAssumeRole) as examples, a session token is added to the access keys, providing time-limited access to AWS resources.

This topic discusses several ways that you enable the SDK to access credentials.

**Topics**
+ [Interactive development work](credentials-temporary.md)
+ [Default credentials provider chain](credentials-chain.md)
+ [Credentials caching](credential-caching.md)
+ [Specify a specific credentials provider](credentials-providers.md)
+ [Use shared configuration profiles](credentials-profiles.md)
+ [Use an external process](credentials-process.md)
+ [Supply credentials in code](credentials-explicit.md)
+ [Read IAM role credentials on Amazon EC2](ec2-iam-roles.md)

# Access credentials for interactive development work using AWS SDK for Java 2.x
<a name="credentials-temporary"></a>

For increased security, AWS recommends that you configure the SDK for Java to [use temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) instead of long-lived credentials. Temporary credentials consist of access keys (access key id and secret access key) and a session token.

Several approaches are available to you to work with temporary credentials. The approach you use, and therefore the configuration that you provide to the SDK, depends on your use case. 

When you do interactive development work with the Java SDK, we recommend that you use AWS Console login credentials. 

## Using console login credentials
<a name="using-con-login-creds"></a>

You can use your existing AWS Management Console sign-in credentials for programmatic access to AWS services. After a browser-based authentication flow, AWS generates temporary credentials that work across local development tools like the AWS CLI and the SDK for Java 2.x.

With this process, you can authenticate using root credentials created during initial account set up, an IAM user, or a federated identity from your identity provider, and the AWS CLI automatically manages the temporary credentials for you. This approach enhances security by eliminating the need to store long-term credentials locally.

When you run the `aws login` command, you can select from your active console sessions, or sign in through the browser-based authentication flow and this will automatically generate temporary credentials. The SDK for Java 2.x will automatically refresh these credentials for up to 12 hours.

**Important**  
In addition to the configuration that you set in the shared config file that works for all projects, each individual Java project requires the following dependency in the Maven `pom.xml` file:  

```
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>signin</artifactId>
</dependency>
```
The `signin` dependency provide the code that enables the SDK for Java 2.x to access and use console login credentials.

For more information on prerequsites, logging in and signing out, see [Login for AWS local development using console credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html) in the *AWS SDK and Tools Refernce Guide*.

## Single-sign-on approach
<a name="single-sign-on-approach"></a>

When you do interactive development work with the Java SDK, you can alternatively use the single sign-on approach. This approach requires the following setup:
+ [Set up through the IAM Identity Center](get-started-auth.md#setup-auth)
+ [Configure a profile in the AWS shared config file](get-started-auth.md#setup-credentials) 
+ using the AWS CLI and [running a command](get-started-auth.md#setup-login-sso) to login and creating an active session

### IAM Identity Center configuration
<a name="credentials-temporary-idc"></a>

When you configure the SDK to use IAM Identity Center single sign-on access as described in [Setup overview](setup.md#setup-overview) in this guide, the SDK uses temporary credentials. 

The SDK uses the IAM Identity Center access token to gain access to the IAM role that is configured with the `sso_role_name` setting in your `config` file. The SDK assumes this IAM role and retrieves temporary credentials to sign AWS service requests.

For more details about how the SDK gets temporary credentials from the configuration, see the [Understanding IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/understanding-sso.html) section of the AWS SDKs and Tools Reference Guide.

**Important**  
In addition to the configuration that you set in the shared `config` file that works for all projects, each individual Java project requires the following dependencies in the Maven `pom.xml` file:  

```
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>sso</artifactId>
</dependency>
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>ssooidc</artifactId>
</dependency>
```
The `sso` and `ssooidc` dependencies provide the code that enables the SDK for Java 2.x to access temporary credentials.

### Retrieve temporary credentials from the AWS access portal
<a name="credentials-temporary-from-portal"></a>

As an alternative to IAM Identity Center single sign-on configuration, you can copy and use temporary credentials available in the AWS access portal. You can use the temporary credentials in a profile or use them as values for system properties and environment variables.

**Set up a local credentials file for temporary credentials**

1. [Create a shared credentials file](https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html)

1. In the credentials file, paste the following placeholder text until you paste in working temporary credentials.

   ```
   [default]
   aws_access_key_id=<value from AWS access portal>
   aws_secret_access_key=<value from AWS access portal>
   aws_session_token=<value from AWS access portal>
   ```

1. Save the file. The file `~/.aws/credentials` should now exist on your local development system. This file contains the [[default] profile](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#file-format-profile) that the SDK for Java uses if a specific named profile is not specified. 

1. [Sign in to the AWS access portal](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosignin.html)

1. Follow these instructions under the [Manual credential refresh](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html#how-to-get-temp-credentials) heading to copy IAM role credentials from the AWS access portal.

   1. For step 2 in the linked instructions, choose `Access keys` for the IAM role name that grants access for your development needs. This role typically has a name like **PowerUserAccess** or ** Developer**.

   1. In the modal dialog box, select the your operating system and copy the contents from **Add a profile to your AWS credentials file**.

1. Paste the copied credentials into your local `credentials` file and remove the generated profile name. Your file should resemble the following.

   ```
   [default]
   aws_access_key_id=AKIAIOSFODNN7EXAMPLE
   aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   aws_session_token=IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZVERYLONGSTRINGEXAMPLE
   ```

1. Save the `credentials` file.

When the SDK for Java creates a service client, it will access these temporary credentials and use them for each request. The settings for the IAM role chosen in step 5a determine [how long the temporary credentials are valid](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html). The maximum duration is twelve hours.

After the temporary credentials expire, repeat steps 4 through 7.

# Default credentials provider chain in the AWS SDK for Java 2.x
<a name="credentials-chain"></a>

The default credentials provider chain in the AWS SDK for Java 2.x automatically searches for AWS credentials in a predefined sequence of locations, allowing applications to authenticate with AWS services without explicitly specifying credential sources.

The default credentials provider chain is implemented by the [DefaultCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.html) class. It sequentially delegates to other credentials provider implementations that check for configuration in various locations. The first credentials provider that can find all necessary configuration elements causes the chain to end.

To use the default credentials provider chain to supply temporary credentials, create a service client builder but don't specify a credentials provider. The following code snippet creates a `DynamoDbClient` that uses the default credentials provider chain to locate and retrieve configuration settings.

```
// Any external Region configuration is overridden.
// The SDK uses the default credentials provider chain because no specific credentials provider is specified.
Region region = Region.US_WEST_2;
DynamoDbClient ddb = 
    DynamoDbClient.builder()
                  .region(region)
                  .build();
```

## Credential settings retrieval order
<a name="credentials-default"></a>

The default credentials provider chain of the SDK for Java 2.x searches for configuration in your environment using a predefined sequence.

1. Java system properties
   + The SDK uses the [SystemPropertyCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/SystemPropertyCredentialsProvider.html) class to load temporary credentials from the `aws.accessKeyId`, `aws.secretAccessKey`, and `aws.sessionToken` Java system properties.
**Note**  
For information on how to set Java system properties, see the [System Properties](https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html) tutorial on the official *Java Tutorials* website.

1. Environment variables
   + The SDK uses the [EnvironmentVariableCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/EnvironmentVariableCredentialsProvider.html) class to load temporary credentials from the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables.

1. Web identity token and IAM role ARN
   + The SDK uses the [WebIdentityTokenFileCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/WebIdentityTokenFileCredentialsProvider.html) class to load credentials by assuming a role using a web identity token.
   + The credentials provider looks for the following environment variables or JVM system properties:
     + `AWS_WEB_IDENTITY_TOKEN_FILE or aws.webIdentityTokenFile`
     + `AWS_ROLE_ARN` or `aws.roleArn`
     + `AWS_ROLE_SESSION_NAME` or `aws.roleSessionName` (optional)
   + After the SDK acquires the values, it calls the AWS Security Token Service (STS) and uses the temporary credentials it returns to sign requests.
   + Runtime environments such as Amazon Elastic Kubernetes Service (EKS) automatically make web identity tokens available to AWS SDKs, enabling applications to obtain temporary AWS credentials.

1. The shared `credentials` and `config` files
   + The SDK uses the [ProfileCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/ProfileCredentialsProvider.html) to load IAM Identity Center single sign-on settings or temporary credentials from the `[default]` profile in the shared `credentials` and `config` files. 

     The AWS SDKs and Tools Reference Guide has [detailed information](https://docs.aws.amazon.com/sdkref/latest/guide/understanding-sso.html#idccredres) about how the SDK for Java works with the IAM Identity Center single sign-on token to get temporary credentials that the SDK uses to call AWS services.
**Note**  
The `credentials` and `config` files are shared by various AWS SDKs and Tools. For more information, see [The .aws/credentials and .aws/config files](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html) in the AWS SDKs and Tools Reference Guide.
   + Because a profile in the shared `credentials` and `config` files can contain many different sets of settings, the `ProfileCredentialsProvider` delegates to a series of other providers to look for settings under the `[default]` profile:
     + **Web identity token credentials** (class `WebIdentityTokenCredentialsProvider`): When the profile contains `role_arn` and `web_identity_token_file`.
     + **SSO credentials** (class `SsoCredentialsProvider`): When the profile contains SSO-related properties such as `sso_role_name`, `sso_account_id`.
     + **Role-based credentials with source profile** (class `StsAssumeRoleCredentialsProvider`): When the profile contains `role_arn` and `source_profile`.
     + **Role-based credentials with credential source** (class `StsAssumeRoleWithSourceCredentialsProvider`): When the profile contains `role_arn` and `credential_source`. 
       + When `credential_source = Environment`: It uses a chain of `SystemPropertyCredentialsProvider` and `EnvironmentVariableCredentialsProvider`
       + When `credential_source = Ec2InstanceMetadata`: It uses `InstanceProfileCredentialsProvider`
       + When `credential_source = EcsContainer`: It uses `ContainerCredentialsProvider`
     + **Console login credentials** (class `LoginCredentialsProvider`): When the profile contains `login_session` 
     + **Process credentials** (class `ProcessCredentialsProvider`): When the profile contains `credential_process`.
     + **Session credentials** (class `StaticSessionCredentialsProvider`): When the profile contains `aws_access_key_id`, `aws_secret_access_key`, and `aws_session_token`.
     + **Basic credentials** (class `StaticCredentialsProvider`): When the profile contains `aws_access_key_id` and `aws_secret_access_key`.

1.  Amazon ECS container credentials
   + The SDK uses the [ContainerCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/ContainerCredentialsProvider.html) class to load temporary credentials using the following environment variables:

     1. `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` or `AWS_CONTAINER_CREDENTIALS_FULL_URI`

     1. `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` or `AWS_CONTAINER_AUTHORIZATION_TOKEN`

   The ECS container agent automatically sets the `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` environment variable, which points to the ECS credentials endpoint. The other environment variables are typically set in specific scenarios where the standard ECS credential endpoint isn't used.

1.  Amazon EC2 instance IAM role-provided credentials
   + The SDK uses the [InstanceProfileCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProvider.html) class to load temporary credentials from the Amazon EC2 metadata service.

1. If the SDK can't find the necessary configuration settings through all this steps listed above, it throws an exception with output similar to the following:

   ```
   software.amazon.awssdk.core.exception.SdkClientException: Unable to load credentials from any of the providers 
   in the chain AwsCredentialsProviderChain(credentialsProviders=[SystemPropertyCredentialsProvider(), 
   EnvironmentVariableCredentialsProvider(), WebIdentityTokenCredentialsProvider(), ProfileCredentialsProvider(), 
   ContainerCredentialsProvider(), InstanceProfileCredentialsProvider()])
   ```

## Use the `DefaultCredentialsProvider` in code
<a name="default-credentials-provider-in-code"></a>

You can explicitly use the default credentials provider chain in your code. This is functionally equivalent to you not specifying a credentials provider at all, since the SDK uses `DefaultCredentialsProvider` by default. However, explicitly using it can make your code more readable and self-documenting. It clearly shows your intention to use the default credentials chain.

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

public class ExplicitDefaultCredentialsExample {
    public static void main(String[] args) {
        // Explicitly create the DefaultCredentialsProvider.
        DefaultCredentialsProvider defaultCredentialsProvider = DefaultCredentialsProvider
                                                                    .builder().build();

        // Use it with any service client.
        S3Client s3Client = S3Client.builder()
            .region(Region.US_WEST_2)
            .credentialsProvider(defaultCredentialsProvider)
            .build();

        // Now you can use the client with the default credentials chain.
        s3Client.listBuckets();
    }
}
```

When you build the default credentials provider you can provide more configuration:

```
DefaultCredentialsProvider customizedProvider = DefaultCredentialsProvider.builder()
    .profileName("custom-profile")  // Use a specific profile if the chain gets to the `ProfileCredentialsProvider` stage.
    .asyncCredentialUpdateEnabled(true)  // Enable async credential updates.
    .build();
```

This approach gives you more control while still providing the convenience of the default credentials chain.

# Credentials caching in the AWS SDK for Java 2.x
<a name="credential-caching"></a>

The AWS SDK for Java 2.x implements credential caching to improve performance and reduce calls to credentials sources. This section explains how credentials caching works and how you can configure it for your applications.

## Understanding credential provider caching
<a name="understanding-credential-provider-caching"></a>

Credential providers in the SDK for Java 2.x use different caching strategies:
+ **Internal credential caching**: Many providers cache credentials that they retrieve.
+ **Automatic refresh**: Providers with cached credentials implement refresh mechanisms.

### Providers with internal credentials caching
<a name="providers-with-internal-caching"></a>

The following credentials providers cache credentials internally, even when you create new instances:
+ **Instance profile credentials provider**: Caches credentials from the Amazon EC2 metadata service.
+ **Container credentials provider**: Caches credentials from the container metadata endpoint.
+ **STS-based providers**: Cache temporary credentials from AWS Security Token Service (STS).
+ **Web identity token providers**: Cache credentials obtained from web identity tokens.
+ **Process credentials provider**: Caches credentials from external processes.

### Providers without internal caching
<a name="providers-without-caching"></a>

The following providers don't implement internal caching:
+ **Environment Variable Credentials Provider**
+ **System Property Credentials Provider**
+ **Static Credentials Provider**

## Configuring credential caching
<a name="configuring-credential-caching"></a>

You can customize caching behavior when building credential providers:

### Stale Time
<a name="stale-time"></a>

Controls when credentials are considered stale and need refreshing:

```
.staleTime(Duration.ofMinutes(2))  // Consider stale 2 minutes before expiration.
```

### Prefetch Time
<a name="prefetch-time"></a>

Determines when to start refreshing credentials before they expire:

```
.prefetchTime(Duration.ofMinutes(10))  // Start refresh 10 minutes before expiration.
```

### Asynchronous Updates
<a name="async-updates"></a>

Enables background credential refreshing:

```
.asyncCredentialUpdateEnabled(true)  // Refresh credentials in background thread.
```

### Session Duration
<a name="session-duration"></a>

For STS-based providers, controls how long temporary credentials remain valid:

```
.refreshRequest(r -> r.durationSeconds(3600))  // 1 hour session.
```

## Caching credentials configuration example
<a name="example-optimized-sts-config"></a>

As an example of configuring caching for a credentials provider implementation, you might want to have the SDK use a background thread to pre-fetch (retrieve in advance) credentials before they expire. That way you can avoid the blocking call that retrieves fresh credentials. 

The following shows an example that creates an `[StsAssumeRoleCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/auth/StsAssumeRoleCredentialsProvider.html)` that uses a background thread to pre-fetch credentials by setting the `[asyncCredentialUpdateEnabled](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/auth/StsCredentialsProvider.BaseBuilder.html#asyncCredentialUpdateEnabled(java.lang.Boolean))` property to `true` on the builder:

```
StsAssumeRoleCredentialsProvider provider = StsAssumeRoleCredentialsProvider.builder()
    .refreshRequest(r -> r
        .roleArn("arn:aws:iam::111122223333:role/example-role")
        .roleSessionName("example-session")
        .durationSeconds(3600))  // 1 hour session
    .staleTime(Duration.ofMinutes(5))  // Consider stale 5 minutes before expiration
    .prefetchTime(Duration.ofMinutes(10))  // Start refresh 10 minutes before expiration
    .asyncCredentialUpdateEnabled(true)  // Refresh in background
    .build();

S3Client s3 = S3Client.builder()
    .credentialsProvider(provider)
    .build();
```

When you invoke an operation on `s3Client` for the first time, an `[AssumeRoleRequest](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/model/AssumeRoleRequest.html)` is sent to the AWS Security Token Service (STS). STS returns temporary credentials that are valid for 15 minutes (900 seconds). The `s3Client` instance uses the cached credentials until it's time to refresh them before the 15 minutes elapse. By default, the SDK attempts to retrieve new credentials for a new session between 5 minutes and 1 minute before the expiration time of the current session. The pre-fetch window is configurable by using the `[prefetchTime](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/auth/StsCredentialsProvider.BaseBuilder.html#prefetchTime(java.time.Duration))` and `[staleTime](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/auth/StsCredentialsProvider.BaseBuilder.html#staleTime(java.time.Duration))` properties.

You can configure the following session-based credentials providers similarly:
+ `StsWebIdentityTokenFileCredentialsProvider`
+ `StsGetSessionTokenCredentialsProvider`
+ `StsGetFederationTokenCredentialsProvider`
+ `StsAssumeRoleWithWebIdentityCredentialsProvider`
+ `StsAssumeRoleWithSamlCredentialsProvider`
+ `StsAssumeRoleCredentialsProvider`
+ `DefaultCredentialsProvider` (when it delegates to credentials provider that uses sessions)
+ `ProcessCredentialsProvider`
+ `WebIdentityTokenFileCredentialsProvider`
+ `ContainerCredentialsProvider`
+ `InstanceProfileCredentialsProvider`

Understanding credential caching helps you optimize your application's performance and reliability when working with AWS services.

# Specify a specific credentials provider in the AWS SDK for Java 2.x
<a name="credentials-providers"></a>

While the default credentials provider chain is convenient for many scenarios, explicitly specifying credentials providers gives you greater control over authentication behavior, performance, and security.

Reasons that you might want to specify a credentials provider might include:
+ The default provider chain checks multiple sources sequentially, which can add latency:

  ```
  // The default provider chain checks might check multiple sources until it finds
  // sufficient configuration.
  S3Client s3Client = S3Client.builder().build();
  
  // You can specify exactly where to look.
  S3Client optimizedClient = S3Client.builder()
      .credentialsProvider(InstanceProfileCredentialsProvider.create())
      .build();
  ```
+ You need to use non-standard locations for accessing credentials configuration:

  ```
  // Use configuration from a custom file location.
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(ProfileCredentialsProvider.builder()
              .profileFile(ProfileFile.builder()
                      .content(Paths.get("/custom/path/to/configuration/file"))
                      .type(ProfileFile.Type.CONFIGURATION) // Expects all non-default profiles to be prefixed with "profile".
                      .build())
              .profileName("custom")
              .build())
      .build();
  ```
+ Use different credentials for different service clients. For example, if your application needs to access multiple AWS accounts or use different permissions for different services:

  ```
  // S3 client using one set of credentials.
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(ProfileCredentialsProvider.create("s3-readonly"))
      .build();
  
  // DynamoDB client using different credentials.
  DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
      .credentialsProvider(ProfileCredentialsProvider.create("dynamodb-admin"))
      .build();
  ```
+ Control credential refresh behavior:

  ```
  // Create a provider with custom refresh behavior.
  StsAssumeRoleCredentialsProvider customRefreshProvider = 
      StsAssumeRoleCredentialsProvider.builder()
          .refreshRequest(AssumeRoleRequest.builder()
              .roleArn("arn:aws:iam::123456789012:role/my-role")
              .roleSessionName("custom-session")
              .build())
          .stsClient(StsClient.create())
          .asyncCredentialUpdateEnabled(true) // Use a background thread to prefetch credentials.
          .build();
  
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(customRefreshProvider)
      .build();
  ```

# Use AWS shared configuration profiles in the AWS SDK for Java 2.x
<a name="credentials-profiles"></a>

Using the shared `config` and `credentials` file, you can set up several profiles. This enables your application to use multiple sets of credentials configuration. The `[default]` profile was mentioned previously. The SDK uses the [ProfileCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/ProfileCredentialsProvider.html) class to load settings from profiles defined in the shared `credentials` file.

The following code snippet demonstrates how to build a service client that uses the settings defined as part of the profile named `my_profile`.

```
Region region = Region.US_WEST_2;
DynamoDbClient ddb = DynamoDbClient.builder()
      .region(region)
      .credentialsProvider(ProfileCredentialsProvider.create("my_profile"))
      .build();
```

## Set a different profile as the default
<a name="set-a-custom-profile-as-the-default"></a>

To set a profile other than the `[default]` profile as the default for your application, set the `AWS_PROFILE` environment variable to the name of your custom profile.

To set this variable on Linux, macOS, or Unix, use `export`:

```
export AWS_PROFILE="other_profile"
```

To set these variables on Windows, use `set`:

```
set AWS_PROFILE="other_profile"
```

Alternatively, set the `aws.profile` Java system property to the name of the profile.

## Reload profile credentials
<a name="profile-reloading"></a>

You can configure any credentials provider that has a `profileFile()` method on its builder to reload profile credentials. These credentials profile classes are: `ProfileCredentialsProvider`, `DefaultCredentialsProvider`, `InstanceProfileCredentialsProvider`, and `ProfileTokenProvider.`

**Note**  
Profile credential reloading works only with the following settings in the profile file : `aws_access_key_id`, `aws_secret_access_key`, and `aws_session_token`.  
Settings such as `region`, `sso_session`, `sso_account_id`, and `source_profile` are ignored.

To configure a supported credentials provider to reload profile settings, provide an instance of [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/profiles/ProfileFileSupplier.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/profiles/ProfileFileSupplier.html) to the `profileFile()` builder method. The following code example demonstrates a `ProfileCredentialsProvider` that reloads credential settings from the `[default]` profile.

```
ProfileCredentialsProvider provider = ProfileCredentialsProvider
    .builder()
    .profileFile(ProfileFileSupplier.defaultSupplier())
    .build();

// Set up a service client with the provider instance.
DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
                    .region(Region.US_EAST_1)
                    .credentialsProvider(provider)
                    .build();

/*
    Before dynamoDbClient makes a request, it reloads the credentials settings 
    by calling provider.resolveCredentials().
*/
```

When `ProfileCredentialsProvider.resolveCredentials()` is called, the SDK for Java reloads the settings. `ProfileFileSupplier.defaultSupplier()` is one of [several convenience implementations](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/profiles/ProfileFileSupplier.html) of `ProfileFileSupplier` provided by the SDK. If your use case requires, you can provide your own implementation.

The following example shows the use of the `ProfileFileSupplier.reloadWhenModified()` convenience method. `reloadWhenModified()` takes a `Path` parameter, which gives you flexibility in designating the source file for the configuration rather than the standard `~/.aws/credentials` (or `config`) location.

The settings will be reloaded when `resolveCredentials()` is called only if SDK determines the file's content has been modified.

```
Path credentialsFilePath = ...

ProfileCredentialsProvider provider = ProfileCredentialsProvider
    .builder()
    .profileFile(ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS))
    .profileName("my-profile")
    .build();
/*
    A service client configured with the provider instance calls provider.resolveCredential()
    before each request.
*/
```

The `ProfileFileSupplier.aggregate()` method merges the contents of multiple configuration files. You decide whether a file is reloaded per call to `resolveCredentials()` or a file's settings are fixed at the time it was first read. 

The following example shows a `DefaultCredentialsProvider` that merges the settings of two files that contain profile settings. The SDK reloads the settings in the file pointed to by the `credentialsFilePath` variable each time `resolveCredentials()` is called and the settings have changed. The settings from the `profileFile` object remain the same.

```
Path credentialsFilePath = ...;
ProfileFile profileFile = ...;

DefaultCredentialsProvider provider = DefaultCredentialsProvider
        .builder()
        .profileFile(ProfileFileSupplier.aggregate(
                ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS),
                ProfileFileSupplier.fixedProfileFile(profileFile)))
        .profileName("my-profile")
        .build();
/*
    A service client configured with the provider instance calls provider.resolveCredential()
    before each request.
*/
```

# Load credentials from an external process using the AWS SDK for Java 2.x
<a name="credentials-process"></a>

**Warning**  
The following describes a method of sourcing temporary credentials from an external process. This can potentially be dangerous, so proceed with caution. We recommend that you use other credential providers if at all possible. If using this option, we recommend that you make sure the `config` file is as locked down as possible using security best practices for your operating system.   
Make sure that your custom credentials tool does not write any secret information to `StdErr`. SDKs and AWS CLI can capture and log such information, potentially exposing it to unauthorized users.

With the SDK for Java 2.x, you can acquire temporary credentials from an external process for custom use cases. There are two ways to configure this functionality.

## Use the `credential_process` setting
<a name="credentials-credential_process"></a>

If you have a method that provides temporary credentials, you can integrate it by adding the `credential_process` setting as part of a profile definition in the `config` file. The value you specify must use the full path to the command file. If the file path contains any spaces, you must surround it with quotation marks.

The SDK calls the command exactly as given and then reads JSON data from `stdout`. 

The following examples show the use of this setting for file paths without spaces and file paths with spaces.

------
#### [ Linux/macOS ]

**No spaces in file path**  

```
[profile process-credential-profile]
credential_process = /path/to/credential/file/credential_file.sh --custom-command custom_parameter
```

**Spaces in file path**  

```
[profile process-credential-profile]
credential_process = "/path/with/space to/credential/file/credential_file.sh" --custom-command custom_parameter
```

------
#### [ Windows ]

**No spaces in file path**  

```
[profile process-credential-profile]
credential_process = C:\Path\To\credentials.cmd --custom_command custom_parameter
```

**Spaces in file path**  

```
[profile process-credential-profile]
credential_process = "C:\Path\With Space To\credentials.cmd" --custom_command custom_parameter
```

------

The following code snippet demonstrates how to build a service client that uses the temporary credentials defined as part of the profile named `process-credential-profile`.

```
Region region = Region.US_WEST_2;
S3Client s3Client = S3Client.builder()
      .region(region)
      .credentialsProvider(ProfileCredentialsProvider.create("process-credential-profile"))
      .build();
```

For detailed information about using an external process as a source of temporary credentials, refer to the [process credentials section](https://docs.aws.amazon.com/sdkref/latest/guide/feature-process-credentials.html) in the AWS SDKs and Tools Reference Guide.

## Use a `ProcessCredentialsProvider`
<a name="credentials-procredprovider"></a>

As an alternative to using settings in the `config` file, you can use the SDK's `[ProcessCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/ProcessCredentialsProvider.html)` to load temporary credentials using Java. 

The following examples show various versions of how to specify an external process using the `ProcessCredentialsProvider` and configuring a service client that uses the temporary credentials.

------
#### [ Linux/macOS ]

**No spaces in file path**  

```
ProcessCredentialsProvider credentials = 
    ProcessCredentialsProvider
        .builder()
        .command("/path/to/credentials.sh optional_param1 optional_param2")
        .build();

S3Client s3 = S3Client.builder()
                      .region(Region.US_WEST_2)
                      .credentialsProvider(credentials)
                      .build();
```

**Spaces in file path**  

```
ProcessCredentialsProvider credentials = 
    ProcessCredentialsProvider
        .builder()
        .command("/path\\ with\\ spaces\\ to/credentials.sh optional_param1 optional_param2")
        .build();

S3Client s3 = S3Client.builder()
                      .region(Region.US_WEST_2)
                      .credentialsProvider(credentials)
                      .build();
```

------
#### [ Windows ]

**No spaces in file path**  

```
ProcessCredentialsProvider credentials = 
    ProcessCredentialsProvider
        .builder()
        .command("C:\\Path\\To\\credentials.exe optional_param1 optional_param2")
        .build();

S3Client s3 = S3Client.builder()
                      .region(Region.US_WEST_2)
                      .credentialsProvider(credentials)
                      .build();
```

**Spaces in file path**  

```
ProcessCredentialsProvider credentials = 
    ProcessCredentialsProvider
        .builder()
        .command("\"C:\\Path\\With Spaces To\\credentials.exe\" optional_param1 optional_param2")
        .build();

S3Client s3 = S3Client.builder()
                      .region(Region.US_WEST_2)
                      .credentialsProvider(credentials)
                      .build();
```

------

## Use IAM Roles Anywhere for authentication
<a name="credentials-iam-roles-anywhere"></a>

[IAM Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/introduction.html) is an AWS service that allows you to obtain temporary AWS credentials for workloads running outside of AWS. It enables secure access to AWS resources from on-premises or other cloud environments.

Before you can authenticate requests with IAM Roles Anywhere, you first need to gather the required information and download the [credential helper tool](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/credential-helper.html). By following the [Getting started](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/getting-started.html) instructions in the IAM Roles Anywhere User Guide, you can create the necessary artifacts. 

The SDK for Java doesn't have a dedicated credentials provider to retrieve temporary credentials from IAM Roles Anywhere, but you can use the credential helper tool along with one of the options to [retrieve credentials from an external process](#credentials-process).

### Use the `credential_process` setting in a profile
<a name="credentials-iam-roles-anywhere-config"></a>

The following snippet in the shared AWS config file shows a profile named `roles_anywhere` that uses the `credential_process` setting:

```
[profile roles_anywhere]
credential_process = ./aws_signing_helper credential-process \
  --certificate /path/to/certificate \
  --private-key /path/to/private-key \
  --trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID \
  --profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \
  --role-arn arn:aws:iam::account:role/role-name-with-path
```

You need to replace the text shown in red with your values after you have assembled all the artifacts. The first element in the setting, `aws_signing_helper`, is the executable of the credential helper tool and `credential-process` is the command.

When you configure a service client to use the `roles_anywhere` profile—as shown in the following code—the SDK caches the temporary credentials and refreshes them before they expire:

```
S3Client s3Client = S3Client.builder()
    .credentialsProvider(ProfileCredentialsProvider.builder()
        .profileName("roles_anywhere").build())
    .build();
```

### Configure a `ProcessCredentialsProvider`
<a name="credentials-iam-roles-anywhere-process"></a>

As shown next, you can use a code-only approach with the `ProcessCredentialsProvider` instead of using profile settings:

```
ProcessCredentialsProvider processCredentialsProvider = ProcessCredentialsProvider.builder()
    .command("""
            ./aws_signing_helper credential-process \
            --certificate /path/to/certificate \
            --private-key /path/to/private-key \
            --trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID \
            --profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \
            --role-arn arn:aws:iam::account:role/role-name-with-path
        """).build();

S3Client s3Client = S3Client.builder()
    .credentialsProvider(processCredentialsProvider)
    .build();
```

Replace the text shown in red with your values after you have assembled all the artifacts. 

# Supply credentials in code using the AWS SDK for Java 2.x
<a name="credentials-explicit"></a>

If the default credential chain or a specific or custom provider or provider chain doesn't work for your application, you can supply temporary credentials directly in code. These can be [IAM role credentials](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html) as[ described above](credentials-temporary.md#credentials-temporary-from-portal) or temporary credentials retrieved from AWS Security Token Service (AWS STS). If you retrieved temporary credentials using AWS STS, provide them to an AWS service client as shown in the following code example.

1. Assume a role by calling `StsClient.assumeRole()`.

1. Create a [StaticCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/StaticCredentialsProvider.html) object and supply it with the `AwsSessionCredentials` object.

1. Configure the service client builder with the `StaticCredentialsProvider` and build the client.

The following example creates an Amazon S3 service client using temporary credentials returned by AWS STS for an IAM assumed role.

```
    // The AWS IAM Identity Center identity (user) who executes this method does not have permission to list buckets.
    // The identity is configured in the [default] profile.
    public static void assumeRole(String roleArn, String roleSessionName) {
        // The IAM role represented by the 'roleArn' parameter can be assumed by identities in two different accounts
        // and the role permits the user to only list buckets.

        // The SDK's default credentials provider chain will find the single sign-on settings in the [default] profile.
        // The identity configured with the [default] profile needs permission to call AssumeRole on the STS service.
        try {
            Credentials tempRoleCredentials;
            try (StsClient stsClient = StsClient.create()) {
                AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                        .roleArn(roleArn)
                        .roleSessionName(roleSessionName)
                        .build();

                AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
                tempRoleCredentials = roleResponse.credentials();
            }
            // Use the following temporary credential items for the S3 client.
            String key = tempRoleCredentials.accessKeyId();
            String secKey = tempRoleCredentials.secretAccessKey();
            String secToken = tempRoleCredentials.sessionToken();

            // List all buckets in the account associated with the assumed role
            // by using the temporary credentials retrieved by invoking stsClient.assumeRole().
            StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider.create(
                    AwsSessionCredentials.create(key, secKey, secToken));
            try (S3Client s3 = S3Client.builder()
                    .credentialsProvider(staticCredentialsProvider)
                    .build()) {
                List<Bucket> buckets = s3.listBuckets().buckets();
                for (Bucket bucket : buckets) {
                    System.out.println("bucket name: " + bucket.name());
                }
            }
        } catch (StsException | S3Exception e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }
```

## Permission set
<a name="credentials-explicit-permission-set"></a>

The following permission set defined in AWS IAM Identity Center allows the identity (user) to perform the following two operations

1. The `GetObject` operation of the Amazon Simple Storage Service.

1. The `AssumeRole` operation of the AWS Security Token Service.

Without assuming the role, the `s3.listBuckets()` method shown in the example would fail.

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"s3:GetObject",
				"sts:AssumeRole"
			],
			"Resource": [
				"*"
			]
		}
	]
}
```

------

## Assumed role
<a name="credentials-explicit-role-to-assume"></a>

### Assumed role permissions policy
<a name="credentials-explicit-role-policy"></a>

The following permissions policy is attached to the role that is assume in the previous example. This permissions policy permits the ability to list all buckets in the same account as the role.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

### Assumed role trust policy
<a name="credentials-explicit-trust-policy"></a>

The following trust policy is attached to the role that is assume in the previous example. The policy allows the role to be assumed by identities (users) in two accounts.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111122223333:root",
                    "arn:aws:iam::555555555555:root"
                ]
            },
            "Action": "sts:AssumeRole",
            "Condition": {}
        }
    ]
}
```

------

# Read IAM role credentials on Amazon EC2 using the SDK for Java 2.x
<a name="ec2-iam-roles"></a>

 You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see [Use an IAM role to grant permissions to applications running on Amazon EC2 instances](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html) in the *IAM User Guide*. 

This topic provides information on how to set up your Java application to run on an EC2 instance and enable the AWS SDK for Java 2.x to acquire IAM role credentials.

## Acquire IAM role credentials from the environment
<a name="default-provider-chain"></a>

If your application creates an AWS service client by using the `create` method (or `builder().build()` methods), the SDK for Java uses the *default credentials provider chain*. The default credentials provider chain searches the execution environment for configuration elements that the SDK can trade for temporary credentials. The [Default credentials provider chain in the AWS SDK for Java 2.x](credentials-chain.md) section describes the full search process.

The final step in the default provider chain is available only when your application runs on an Amazon EC2 instance. In this step, the SDK uses an `InstanceProfileCredentialsProvider` to read the IAM role defined in the EC2 instance profile. The SDK then acquires temporary credentials for that IAM role.

Although these credentials are temporary and would eventually expire, an `InstanceProfileCredentialsProvider` periodically refreshes them for you so that they continue to allow access to AWS.

## Acquire IAM role credentials programmatically
<a name="programmatic-configuration-for-IAM-role"></a>

As an alternative to the default credentials provider chain that eventually uses an `InstanceProfileCredentialsProvider` on EC2, you can configure a service client explicitly with an `InstanceProfileCredentialsProvider`. This approach is shown in the following snippet.

```
S3Client s3 = S3Client.builder()
       .credentialsProvider(InstanceProfileCredentialsProvider.create())
       .build();
```

## Securely acquire IAM role credentials
<a name="securely-read-IAM-role_credentials"></a>

By default, EC2 instances run [IMDS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html) (Instance Metadata Service) that allows the SDK's `InstanceProfileCredentialsProvider` to access information such as the IAM role that has been configured. EC2 instances run two versions of IMDS by default:
+ Instance Metadata Service Version 1 (IMDSv1) – a request/response method
+ Instance Metadata Service Version 2 (IMDSv2) – a session-oriented method

[IMDSv2 is a more secure approach](https://aws.amazon.com/blogs/security/defense-in-depth-open-firewalls-reverse-proxies-ssrf-vulnerabilities-ec2-instance-metadata-service/) than IMDSv1.

By default, the Java SDK first tries IMDSv2 to get the IAM role, but if that fails, it tries IMDSv1. However, since IMDSv1 is less secure, AWS recommends the use of IMDSv2 only and to disable the SDK from trying IMDSv1. 

To use the more secure approach, disable the SDK from using IMDSv1 by providing one of the following settings with a value of `true`.
+ Environment variable: `AWS_EC2_METADATA_V1_DISABLED`
+ JVM system property: aws.`disableEc2MetadataV1`
+ Shared config file setting: `ec2_metadata_v1_disabled`

With one of these settings set to `true`, the SDK does not load IMDS role credentials by using IMDSv1 if the initial IMDSv2 call fails.