

# Authentication and access using AWS SDKs and tools
<a name="access"></a>

When you develop an AWS SDK application or use AWS tools to use AWS services, you must establish how your code or tool authenticates with AWS. You can configure programmatic access to AWS resources in different ways, depending on the environment the code runs in and the AWS access available to you. 

The options below are a part of the [credential provider chain](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html#credentialProviderChain). This means that by configuring your shared AWS `config` and `credentials` files accordingly, your AWS SDK or tool will automatically discover and use that method of authentication.

## Choose a method to authenticate your application code
<a name="authDecisionTree"></a>

Choose a method to authenticate the calls made to AWS by your application.

### Are you running code INSIDE an AWS service (such as Amazon EC2, Lambda, Amazon ECS, Amazon EKS, CodeBuild)?
<a name="a"></a>

If your code runs on AWS, credentials can be made automatically available to your application. For example, if your application is hosted on Amazon Elastic Compute Cloud, and there is an IAM role associated with that resource, the credentials are automatically made available to your application. Likewise, if you use Amazon ECS or Amazon EKS containers, the credentials set for the IAM role can be automatically obtained by the code running inside the container through the SDK's [credential provider chain](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html#credentialProviderChain).

#### Is your code in an Amazon Elastic Compute Cloud instance?
<a name="a1"></a>

[Using IAM roles to authenticate applications deployed to Amazon EC2](access-iam-roles-for-ec2.md) – Use IAM roles to securely run your application on an Amazon EC2 instance.

#### Is your code in an AWS Lambda function?
<a name="a2"></a>

Lambda creates an execution role with minimal permissions when you [create a Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html). The AWS SDK or tool then automatically uses the IAM role attached to the Lambda at runtime, via the Lambda execution environment.

#### Is your code in Amazon Elastic Container Service (on Amazon EC2 or AWS Fargate for Amazon ECS)?
<a name="a3"></a>

Use IAM Role for Task. You must [create a task role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) and specify that role in your [Amazon ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). The AWS SDK or tool then automatically uses the IAM role assigned to the task at runtime, via the Amazon ECS metadata.

#### Is your code in Amazon Elastic Kubernetes Service?
<a name="a4"></a>

We recommend you use [Amazon EKS Pod Identities](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html).

Note: If you feel that [IAM roles for service accounts](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) (IRSA) might better suit your unique needs, see [Comparing EKS Pod Identity and IRSA](https://docs.aws.amazon.com/eks/latest/userguide/service-accounts.html#service-accounts-iam) in the **Amazon EKS User Guide**.

#### Is your code running in AWS CodeBuild
<a name="a5"></a>

See [Using identity-based policies for CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html).

#### Is your code in another AWS service?
<a name="a6"></a>

See the dedicated guide for your AWS service. When you run code on AWS, the SDK [credential provider chain](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html#credentialProviderChain) can automatically obtain and refresh credentials for you.

### Are you creating mobile applications or client-based web applications?
<a name="b"></a>

If you are creating mobile applications or client-based web applications that require access to AWS, build your app so that it requests temporary AWS security credentials dynamically by using web identity federation. 

With web identity federation, you don't need to create custom sign-in code or manage your own user identities. Instead, app users can sign in using a well-known external identity provider (IdP), such as Login with Amazon, Facebook, Google, or any other OpenID Connect (OIDC)-compatible IdP. They can receive an authentication token, and then exchange that token for temporary security credentials in AWS that map to an IAM role with permissions to use the resources in your AWS account. 

To learn how to configure this for your SDK or tool, see [Assuming a role with web identity or OpenID Connect to authenticate AWS SDKs and tools](access-assume-role-web.md). 

For mobile applications, consider using Amazon Cognito. Amazon Cognito acts as an identity broker and does much of the federation work for you. For more information, see [Using Amazon Cognito for mobile apps](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_cognito.html) in the *IAM User Guide*. 

### Are you developing and running the code LOCALLY?
<a name="c"></a>

We recommend [Using console credentials to authenticate AWS SDKs and tools](access-login.md).

After a quick browser-based authentication flow, AWS automatically generates temporary credentials that work across local development tools like the AWS CLI, AWS Tools for PowerShell and AWS SDKs. 

#### If you use Identity Center for AWS account access
<a name="idc"></a>

Use IAM Identity Center to authenticate AWS SDK and tools if you already have access to AWS accounts and/or need to manage access for your workforce. As a security best practice, we recommend using AWS Organizations with IAM Identity Center to manage access across all your AWS accounts. You can create users in IAM Identity Center, use Microsoft Active Directory, use a SAML 2.0 identity provider (IdP), or individually federate your IdP to AWS accounts. To check if your Region supports IAM Identity Center, see [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md)IAM Identity Center endpoints and quotas in the Amazon Web Services General Reference.

#### If you are looking for other ways to authenticate
<a name="owa"></a>

Create a least-privileged IAM user with permissions to `sts:AssumeRole` into your target role. Then configure your profile to assume a role using a `source_profile` set up for that user.

You can also use temporary IAM credentials via environment variables or the shared AWS credentials file. See Using short-term credentials to authenticate AWS SDKs and tools.

Note: In sandbox or learning environments only, you can consider Using long-term credentials to authenticate AWS SDKs and tools.

### Is this code running on-premise or in a hybrid/on-demand VM (such as server that reads from or writes to Amazon S3, or Jenkins deploying to the cloud)?
<a name="d"></a>

#### Are you using X.509 client certificates?
<a name="d1"></a>

Yes: See [Using IAM Roles Anywhere to authenticate AWS SDKs and tools](access-rolesanywhere.md). You can use IAM Roles Anywhere to obtain temporary security credentials in IAM for workloads such as servers, containers, and applications that run outside of AWS. To use IAM Roles Anywhere, your workloads must use X.509 certificates.

#### Can the environment securely connect to a federated identity provider (such as Microsoft Entra or Okta) to request temporary AWS credentials?
<a name="d2"></a>

##### Yes: Use [Process credential provider](feature-process-credentials.md)
<a name="d2a"></a>

Use [Process credential provider](feature-process-credentials.md) to retrieve credentials automatically at runtime. These systems might use a helper tool or plugin to obtain the credentials, and might assume an IAM role behind the scenes using `sts:AssumeRole`.

##### No: Use temporary credentials injected via AWS Secrets Manager
<a name="d2b"></a>

Use temporary credentials injected via AWS Secrets Manager. For options to obtain short-lived access keys, see [Request temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) in the *IAM User Guide*. For options on storing these temporary credentials, see [AWS access keys](feature-static-credentials.md).

You can use these credentials to securely retrieve broader application permissions from [Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html), where your production secrets or long-lived role-based credentials can be stored.

### Are you using a third-party tool not in AWS?
<a name="e"></a>

Use the documentation written by your third-party provider for best guidance on obtaining credentials.

#### If your third-party has not provided documentation, can you inject temporary credentials securely?
<a name="e1"></a>

Yes: Use environment variables and temporary AWS STS credentials.

No: Use static access keys stored in encrypted secret manager (last resort).

## Authentication methods
<a name="authOptions"></a>

**Authentication methods for code running within an AWS environment **

If your code runs on AWS, credentials can be made automatically available to your application. For example, if your application is hosted on Amazon Elastic Compute Cloud, and there is an IAM role associated with that resource, the credentials are automatically made available to your application. Likewise, if you use Amazon ECS or Amazon EKS containers, the credentials set for the IAM role can be automatically obtained by the code running inside the container through the SDK's credential provider chain.
+ [Using IAM roles to authenticate applications deployed to Amazon EC2](access-iam-roles-for-ec2.md) – Use IAM roles to securely run your application on an Amazon EC2 instance. 
+  You can programmatically interact with AWS using IAM Identity Center in the following ways:
  + Use [AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/) to run AWS CLI commands from the console.
  + To try cloud-based collaboration space for software development teams, consider using [Amazon CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/welcome.html). 

**Authentication through a web-based identity provider - Mobile or client-based web applications**

If you are creating mobile applications or client-based web applications that require access to AWS, build your app so that it requests temporary AWS security credentials dynamically by using web identity federation. 

With web identity federation, you don't need to create custom sign-in code or manage your own user identities. Instead, app users can sign in using a well-known external identity provider (IdP), such as Login with Amazon, Facebook, Google, or any other OpenID Connect (OIDC)-compatible IdP. They can receive an authentication token, and then exchange that token for temporary security credentials in AWS that map to an IAM role with permissions to use the resources in your AWS account. 

To learn how to configure this for your SDK or tool, see [Assuming a role with web identity or OpenID Connect to authenticate AWS SDKs and tools](access-assume-role-web.md). 

For mobile applications, consider using Amazon Cognito. Amazon Cognito acts as an identity broker and does much of the federation work for you. For more information, see [Using Amazon Cognito for mobile apps](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_cognito.html) in the *IAM User Guide*. 

**Authentication methods for code running locally (not in AWS) **
+ [Using console credentials to authenticate AWS SDKs and tools](access-login.md) – This feature works with both AWS Command Line Interface and Tools for PowerShell and gives you refreshable credentials that work across local development tools like the AWS CLI, Tools for PowerShell and AWS.
+ [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md) – As a security best practice, we recommend using AWS Organizations with IAM Identity Center to manage access across all your AWS accounts. You can create users in AWS IAM Identity Center, use Microsoft Active Directory, use a SAML 2.0 identity provider (IdP), or individually federate your IdP to AWS accounts. To check if your Region supports IAM Identity Center, see [AWS IAM Identity Center endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sso.html) in the *Amazon Web Services General Reference*. 
+ [Using IAM Roles Anywhere to authenticate AWS SDKs and tools](access-rolesanywhere.md) – You can use IAM Roles Anywhere to obtain temporary security credentials in IAM for workloads such as servers, containers, and applications that run outside of AWS. To use IAM Roles Anywhere, your workloads must use X.509 certificates. 
+  [Assuming a role with AWS credentials to authenticate AWS SDKs and tools](access-assume-role.md) – You can assume an IAM role to temporarily access AWS resources that you might not have access to otherwise. 
+  [Using AWS access keys to authenticate AWS SDKs and tools](access-users.md) – Other options that might be less convenient or might increase the security risk to your AWS resources. 

**More information about access management**

The *IAM User Guide* has the following information about securely controlling access to AWS resources:
+ [IAM Identities (users, user groups, and roles)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) – Understand the basics of identities in AWS.
+ [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) – Security recommendations to follow when developing AWS applications according to the [shared-responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/).

The *Amazon Web Services General Reference* has foundational basics on the following:
+ [Understanding and getting your AWS credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html) – Access key options and management practices for both console and programmatic access.

**IAM Identity Center trusted identity propagation (TIP) plugin to access AWS services**
+ [Using the TIP plugin to access AWS services](access-tip.md) – If you are creating an application for Amazon Q Business or other service that supports trusted identity propagation, and are using the AWS SDK for Java or the AWS SDK for JavaScript, you can use the TIP plugin for a streamlined authorization experience. 

## AWS Builder ID
<a name="bid"></a>

Your AWS Builder ID complements any AWS accounts you might already own or want to create. While an AWS account acts as a container for AWS resources you create and provides a security boundary for those resources, your AWS Builder ID represents you as an individual. You can sign in with your AWS Builder ID to access developer tools and services such as Amazon Q and Amazon CodeCatalyst.
+ [Sign in with AWS Builder ID](https://docs.aws.amazon.com/signin/latest/userguide/sign-in-aws_builder_id.html) in the *AWS Sign-In User Guide* – Learn how to create and use an AWS Builder ID and learn what the Builder ID provides.
+ [CodeCatalyst concepts - AWS Builder ID](https://docs.aws.amazon.com/codecatalyst/latest/userguide/concepts.html#sign-in-concept) in the *Amazon CodeCatalyst User Guide* – Learn how CodeCatalyst uses an AWS Builder ID.

# Using console credentials to authenticate AWS SDKs and tools
<a name="access-login"></a>

Using console credentials is the recommended method of providing AWS credentials when developing an AWS application in your local environment or other non-AWS compute service environments. If you are developing on an AWS resource, such as Amazon Elastic Compute Cloud (Amazon EC2) or AWS CloudShell, we recommend getting credentials from that service instead.

You can also authenticate through IAM Identity Center [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md). This option is a common way for organizations to manage access for their workforce and requires Identity Center to be enabled.

## How does it work?
<a name="access-login-how"></a>

[Login for AWS local development using console credentials ](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) lets you 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, Tools for PowerShell and AWS SDKs. This feature simplifies the process of configuring and managing AWS CLI credentials, especially if you prefer interactive authentication over managing long-term access keys.

With this process, you can authenticate using your root credentials created during initial account setup, IAM users, or a federated identity from your identity provider.

If you use SDKs for development, the SDK clients will use the temporary credentials through the [AWS SDKs and Tools standardized credential providers](standardized-credentials.md). You can also configure the [Login credentials provider](feature-login-credentials.md).

Authenticating via the login command is supported by both AWS CLI and Tools for PowerShell:
+ [Login for AWS local development using console credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html)
+ [Login using console credentials](https://docs.aws.amazon.com/powershell/v5/userguide/creds-idc.html#login-con-creds) in the AWS Tools for PowerShell user guide

# Using IAM Identity Center to authenticate AWS SDK and tools
<a name="access-sso"></a>

 AWS IAM Identity Center can be used to provide AWS credentials when developing an AWS application on a non-AWS compute service environments. If you are developing on an AWS resource, such as Amazon Elastic Compute Cloud (Amazon EC2) or AWS Cloud9, we recommend getting credentials from that service instead.

Use IAM Identity Center authentication if you already use Identity Center for AWS account access or need to manage access for an organization. 

In this tutorial, you establish IAM Identity Center access and will configure it for your SDK or tool by using the AWS access portal and the AWS CLI.
+ The AWS access portal is the web location where you manually sign in to the IAM Identity Center. The format of the URL is `d-xxxxxxxxxx.awsapps.com/start`or `your_subdomain.awsapps.com/start`. When signed in to the AWS access portal, you can view AWS accounts and roles that have been configured for that user. This procedure uses the AWS access portal to get configuration values you need for the SDK/tool authentication process. 
+ The AWS CLI is used to configure your SDK or tool to use IAM Identity Center authentication for API calls made by your code. This one-time process updates your shared AWS `config` file, that is then used by your SDK or tool when you run your code. 

## Prerequisites
<a name="prereq-auth"></a>

Before starting this procedure, you should have completed the following:
+ If you do not have an AWS account, [sign up for an AWS account](https://portal.aws.amazon.com/billing/signup).
+ If you haven't enabled IAM Identity Center yet, [enable IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/get-set-up-for-idc.html) by following the instructions in the *AWS IAM Identity Center User Guide*.

## Configure programmatic access using IAM Identity Center
<a name="idcGettingStarted"></a>

### Step 1: Establish access and select appropriate permission set
<a name="establishAccess"></a>

Choose one of the following methods to access your AWS credentials.

#### I do not have established access through IAM Identity Center
<a name="idc-access"></a>

1. Add a user and add administrative permissions by following the [Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com/singlesignon/latest/userguide/quick-start-default-idc.html) procedure in the *AWS IAM Identity Center User Guide*. 

1. The `AdministratorAccess` permission set should not be used for regular development. Instead, we recommend using the predefined `PowerUserAccess` permission set, unless your employer has created a custom permission set for this purpose.

   Follow the same [Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com/singlesignon/latest/userguide/quick-start-default-idc.html) procedure again, but this time:
   + Instead of creating the `Admin team` group, create a `Dev team` group, and substitute this thereafter in the instructions.
   + You can use the existing user, but the user must be added to the new `Dev team` group.
   + Instead of creating the `AdministratorAccess` permission set, create a `PowerUserAccess` permission set, and substitute this thereafter in the instructions.

   When you are done, you should have the following:
   + A `Dev team` group.
   + An attached `PowerUserAccess` permission set to the `Dev team` group.
   + Your user added to the `Dev team` group.

1. Exit the portal and sign in again to see your AWS accounts and options for `Administrator` or `PowerUserAccess`. Select `PowerUserAccess` when working with your tool/SDK. 

#### I already have access to AWS through a federated identity provider managed by my employer (such as Microsoft Entra or Okta)
<a name="federated-access"></a>

Sign in to AWS through your identity provider's portal. If your Cloud Administrator has granted you `PowerUserAccess` (developer) permissions, you see the AWS accounts that you have access to and your permission set. Next to the name of your permission set, you see options to access the accounts manually or programmatically using that permission set. 

Custom implementations might result in different experiences, such as different permission set names. If you're not sure which permission set to use, contact your IT team for help. 

#### I already have access to AWS through the AWS access portal managed by my employer
<a name="accessportal-access"></a>

Sign in to AWS through the AWS access portal. If your Cloud Administrator has granted you `PowerUserAccess` (developer) permissions, you see the AWS accounts that you have access to and your permission set. Next to the name of your permission set, you see options to access the accounts manually or programmatically using that permission set. 

#### I already have access to AWS through a federated custom identity provider managed by my employer
<a name="customfederated-access"></a>

Contact your IT team for help.

### Step 2: Configure SDKs and tools to use IAM Identity Center
<a name="configureAccess"></a>

1.  On your development machine, install the latest AWS CLI. 

   1. See [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) in the *AWS Command Line Interface User Guide*. 

   1.  (Optional) To verify that the AWS CLI is working, open a command prompt and run the `aws --version` command. 

1. Sign in to the AWS access portal. Your employer may provide this URL or you may get it in an email following **Step 1: Establish access**. If not, find your **AWS access portal URL** on the **Dashboard** of [https://console.aws.amazon.com/singlesignon/](https://console.aws.amazon.com/singlesignon/). 

   1. In the AWS access portal, in the **Accounts** tab, select the individual account to manage. The roles for your user are displayed. Choose **Access keys** to get credentials for command line or programmatic access for the appropriate permission set. Use the predefined `PowerUserAccess` permission set, or whichever permission set you or your employer has created to apply least-privilege permissions for development. 

   1. In the **Get credentials** dialog box, choose either **MacOS and Linux** or **Windows**, depending on your operating system.

   1. Choose the **IAM Identity Center credentials** method to get the `Issuer URL` and `SSO Region` values that you need for the next step. Note: `SSO Start URL` can be used interchangeably with `Issuer URL`.

1. In the AWS CLI command prompt, run the `aws configure sso` command. When prompted, enter the configuration values that you collected in the previous step. For details on this AWS CLI command, see [Configure your profile with the `aws configure sso` wizard](https://docs.aws.amazon.com/cli/latest/userguide/sso-configure-profile-token.html#sso-configure-profile-token-auto-sso). 

   1. For the prompt `SSO Start URL`, enter the value you obtained for `Issuer URL`. 

   1.  For **CLI profile name**, we recommend entering *default* when you are getting started. For information about how to set non-default (named) profiles and their associated environment variable, see [Profiles](file-format.md#file-format-profile). 

1. (Optional) In the AWS CLI command prompt, confirm the active session identity by running the `aws sts get-caller-identity` command. The response should show the IAM Identity Center permission set that you configured. 

1. If you are using an AWS SDK, create an application for your SDK in your development environment.

   1. For some SDKs, additional packages such as `SSO` and `SSOOIDC` must be added to your application before you can use IAM Identity Center authentication. For details, see your specific SDK.

   1.  If you previously configured access to AWS, review your shared AWS `credentials` file for any [AWS access keys](feature-static-credentials.md). You must remove any static credentials before the SDK or tool will use the IAM Identity Center credentials because of the [Understand the credential provider chain](standardized-credentials.md#credentialProviderChain) precedence. 

 For a deep dive into how the SDKs and tools use and refresh credentials using this configuration, see [How IAM Identity Center authentication is resolved for AWS SDKs and tools](understanding-sso.md). 

To configure IAM Identity Center provider settings directly in the shared `config` file, see [IAM Identity Center credential provider](feature-sso-credentials.md) in this guide.

## Refreshing portal access sessions
<a name="refreshSession"></a>

Your access will eventually expire and the SDK or tool will encounter an authentication error. When this expiration occurs depends on your configured session lengths. To refresh the access portal session again when needed, use the AWS CLI to run the `aws sso login` command. 

You can extend both the IAM Identity Center access portal session duration and the permission set session duration. This lengthens the amount of time that you can run code before you need to manually sign in again with the AWS CLI. For more information, see the following topics in the *AWS IAM Identity Center User Guide*:
+ **IAM Identity Center session duration** – [Configure the duration of your users' AWS access portal sessions](https://docs.aws.amazon.com/singlesignon/latest/userguide/configure-user-session.html) 
+ **Permission set session duration** – [Set session duration ](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html)

# How IAM Identity Center authentication is resolved for AWS SDKs and tools
<a name="understanding-sso"></a>



## Relevant IAM Identity Center terms
<a name="ssoterms"></a>

The following terms help you understand the process and configuration behind AWS IAM Identity Center. The documentation for AWS SDK APIs uses different names than IAM Identity Center for some of these authentication concepts. It's helpful to know both names. 

The following table shows how alternative names relate to each other.


| IAM Identity Center name | SDK API name | Description | 
| --- | --- | --- | 
| Identity Center  | sso  | Although AWS Single Sign-On is renamed, the sso API namespaces will keep their original name for backward compatibility purposes. For more information, see [IAM Identity Center rename](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed) in the AWS IAM Identity Center User Guide. | 
| IAM Identity Center consoleAdministrative console |   | The console you use to configure single sign-on.  | 
| AWS access portal URL  |  | A URL unique to your IAM Identity Center account, like https://xxx.awsapps.com/start. You sign in to this portal using your IAM Identity Center sign-in credentials.  | 
| IAM Identity Center Access Portal session  | Authentication session  | Provides a bearer access token to the caller.  | 
| Permission set session  |   | The IAM session that the SDK uses internally to make the AWS service calls. In informal discussions, you might see this incorrectly referred to as "role session." | 
| Permission set credentials  | AWS credentialssigv4 credentials  | The credentials the SDK actually uses for most AWS service calls (specifically, all sigv4 AWS service calls). In informal discussions, you might see this incorrectly referred to as "role credentials." | 
| IAM Identity Center credential provider  | SSO credential provider  | How you get the credentials, such as the class or module providing the functionality.  | 

## Understand SDK credential resolution for AWS services
<a name="idccredres"></a>

The IAM Identity Center API exchanges bearer token credentials for sigv4 credentials. Most AWS services are sigv4 APIs, with a few exceptions like Amazon CodeWhisperer and Amazon CodeCatalyst. The following describes the credential resolution process for supporting most AWS service calls for your application code through AWS IAM Identity Center. 

### Start an AWS access portal session
<a name="idccredres1"></a>
+ Start the process by signing in to the session with your credentials.
  + Use the `aws sso login` command in the AWS Command Line Interface (AWS CLI). This starts a new IAM Identity Center session if you don't already have an active session.
+ When you start a new session, you receive a refresh token and access token from IAM Identity Center. The AWS CLI also updates an SSO cache JSON file with a new access token and refresh token and makes it available for use by SDKs.
+ If you already have an active session, the AWS CLI command reuses the existing session and will expire whenever the existing session expires. To learn how to set the length of an IAM Identity Center session, see [Configure the duration of your users' AWS access portal sessions](https://docs.aws.amazon.com/singlesignon/latest/userguide/configure-user-session.html) in the *AWS IAM Identity Center User Guide*. 
  + The maximum session length has been extended to 90 days to reduce the need for frequent sign-ins.

### How the SDK gets credentials for AWS service calls
<a name="idccredres2"></a>

SDKs provide access to AWS services when you instantiate a client object per service. When the selected profile of the shared AWS `config` file is configured for IAM Identity Center credential resolution, IAM Identity Center is used to resolve credentials for your application. 
+ The [credential resolution process](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html#credentialProviderChain) is completed during runtime when a client is created.

To retrieve credentials for sigv4 APIs using IAM Identity Center single sign-on, the SDK uses the IAM Identity Center access token to get an IAM session. This IAM session is called a permission set session, and it provides AWS access to the SDK by assuming an IAM role. 
+  The permission set session duration is set independently from the IAM Identity Center session duration.
  + To learn how to set the permission set session duration, see [Set session duration](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html) in the *AWS IAM Identity Center User Guide*.
+  Be aware that the permission set credentials are also referred to as *AWS credentials* and *sigv4 credentials* in most AWS SDK API documentation.

The permission set credentials are returned from a call to [getRoleCredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) of the IAM Identity Center API to the SDK. The SDK's client object uses that assumed IAM role to make calls to the AWS service, such as asking Amazon S3 to list the buckets in your account. The client object can continue to operate using those permission set credentials until the permission set session expires. 

### Session expiration and refresh
<a name="idccredres3"></a>

When using the [SSO token provider configuration](feature-sso-credentials.md#sso-token-config), the hourly access token obtained from IAM Identity Center is automatically refreshed using the refresh token.
+ If the access token is expired when the SDK tries to use it, the SDK uses the refresh token to try to get a new access token. The IAM Identity Center compares the refresh token to your IAM Identity Center access portal session duration. If the refresh token is not expired, the IAM Identity Center responds with another access token.
+ This access token can be used to either refresh the permission set session of existing clients, or to resolve credentials for new clients. 

However, if the IAM Identity Center access portal session is expired, then no new access token is granted. Therefore, the permission set duration cannot be renewed. It will expire (and access will be lost) whenever the cached permission set session length times out for existing clients. 

Any code that creates a new client will fail authentication as soon as the IAM Identity Center session expires. This is because the permission set credentials are not cached. Your code won't be able to create a new client and complete the credential resolution process until you have a valid access token. 

To recap, when the SDK needs new permission set credentials, the SDK first checks for any valid, existing credentials and uses those. This applies whether the credentials are for a new client or for an existing client with expired credentials. If credentials aren't found or they're not valid, then the SDK calls the IAM Identity Center API to get new credentials. To call the API, it needs the access token. If the access token is expired, the SDK uses the refresh token to try to get a new access token from the IAM Identity Center service. This token is granted if your IAM Identity Center access portal session is not expired. 

# Using IAM Roles Anywhere to authenticate AWS SDKs and tools
<a name="access-rolesanywhere"></a>

You can use IAM Roles Anywhere to get temporary security credentials in IAM for workloads such as servers, containers, and applications that run outside of AWS. To use IAM Roles Anywhere, your workloads must use X.509 certificates. Your Cloud Administrator should provide the certificate and private key needed to configure IAM Roles Anywhere as your credential provider.

## Step 1: Configure IAM Roles Anywhere
<a name="config-ira"></a>

IAM Roles Anywhere provides a way to get temporary credentials for a workload or process that runs outside of AWS. A trust anchor is established with the certificate authority to get temporary credentials for the associated IAM role. The role sets the permissions your workload will have when your code authenticates with IAM Roles Anywhere.

For steps to set up the trust anchor, IAM role, and IAM Roles Anywhere profile, see [Creating a trust anchor and profile in AWS Identity and Access Management Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/getting-started.html) in the *IAM Roles Anywhere User Guide*.

**Note**  
A *profile* in the *IAM Roles Anywhere User Guide* refers to a unique concept within the IAM Roles Anywhere service. It's not related to the profiles within the shared AWS `config` file. 

## Step 2: Use IAM Roles Anywhere
<a name="use-ira"></a>

To get temporary security credentials from IAM Roles Anywhere, use the credential helper tool provided by IAM Roles Anywhere. The credential tool implements the signing process for IAM Roles Anywhere.

For instructions to download the credential helper tool, see [Obtaining temporary security credentials from AWS Identity and Access Management Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/credential-helper.html) in the *IAM Roles Anywhere User Guide*.

To use temporary security credentials from IAM Roles Anywhere with AWS SDKs and the AWS CLI, you can configure `credential_process` setting in the shared AWS `config` file. The SDKs and AWS CLI support a process credential provider that uses `credential_process` to authenticate. The following shows the general structure to set `credential_process`.

```
credential_process = [path to helper tool] [command] [--parameter1 value] [--parameter2 value] [...]  
```

The `credential-process` command of the helper tool returns temporary credentials in a standard JSON format that is compatible with the `credential_process` setting. Note that the command name contains a hyphen but the setting name contains an underscore. The command requires the following parameters:
+ `private-key` – The path to the private key that signed the request. 
+ ` certificate` – The path to the certificate. 
+ `role-arn` – The ARN of the role to get temporary credentials for. 
+ `profile-arn` – The ARN of the profile that provides a mapping for the specified role. 
+ `trust-anchor-arn` – The ARN of the trust anchor used to authenticate. 

Your Cloud Administrator should provide the certificate and private key. All three ARN values can be copied from the AWS Management Console. The following example shows a shared `config` file that configures retrieving temporary credentials from the helper tool. 

```
[profile dev]
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_ID
```

 For optional parameters and additional helper tool details, see [IAM Roles Anywhere Credential Helper](https://github.com/aws/rolesanywhere-credential-helper#readme) on GitHub. 

For details on the SDK configuration setting itself and the process credential provider, see [Process credential provider](feature-process-credentials.md) in this guide.

# Assuming a role with AWS credentials to authenticate AWS SDKs and tools
<a name="access-assume-role"></a>

Assuming a role involves using a set of temporary security credentials to access AWS resources that you might not have access to otherwise. These temporary credentials consist of an access key ID, a secret access key, and a security token. To learn more about AWS Security Token Service (AWS STS) API requests, see [Actions](https://docs.aws.amazon.com/STS/latest/APIReference/API_Operations.html) in the *AWS Security Token Service API Reference*. 

To set up your SDK or tool to assume a role, you must first create or identify a specific *role* to assume. IAM roles are uniquely identified by a role Amazon Resource Name ([ARN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html)). Roles establish trust relationships with another entity. The trusted entity that uses the role might be an AWS service or another AWS account. To learn more about IAM roles, see [Using IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) in the *IAM User Guide*. 

After the IAM role is identified, if you are trusted by that role, you can configure your SDK or tool to use the permissions that are granted by the role. 

**Note**  
It is an AWS best practice to use Regional endpoints whenever possible and to configure your [AWS Region](feature-region.md). 

## Assume an IAM role
<a name="credOrSourceAssumeRole"></a>

When assuming a role, AWS STS returns a set of temporary security credentials. These credentials are sourced from another profile or from the instance or container that your code is running in. Most commonly this type of assuming a role is used when you have AWS credentials for one account, but your application needs access to resources in another account. 

### Step 1: Set up an IAM role
<a name="credOrSourceAssumeRole_step1"></a>

To set up your SDK or tool to assume a role, you must first create or identify a specific role to assume. IAM roles are uniquely identified using a role [ARN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html). Roles establish trust relationships with another entity, typically within your account or for cross-account access. To set this up, see [Creating IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html) in the *IAM User Guide*.

### Step 2: Configure the SDK or tool
<a name="credOrSourceAssumeRole_step2"></a>

Configure the SDK or tool to source credentials from `credential_source` or `source_profile`. 

Use `credential_source` to source credentials from an Amazon ECS container, an Amazon EC2 instance, or from environment variables. 

Use `source_profile` to source credentials from another profile. `source_profile` also supports role chaining, which is hierarchies of profiles where an assumed role is then used to assume another role.

When you specify this in a profile, the SDK or tool automatically makes the corresponding AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API call for you. To retrieve and use temporary credentials by assuming a role, specify the following configuration values in the shared AWS `config` file. For more details on each of these settings, see the [Assume role credential provider settings](feature-assume-role-credentials.md#feature-assume-role-credentials-settings) section. 
+ `role_arn` - From the IAM role you created in Step 1
+ Configure either `credential_source` or `source_profile`
+ (Optional) `duration_seconds`
+ (Optional) `external_id`
+ (Optional) `mfa_serial`
+ (Optional) `role_session_name` 

The following examples show the configuration of both assume role options in a shared `config` file:

```
role_arn = arn:aws:iam::123456789012:role/my-role-name
credential_source = Ec2InstanceMetadata
```

```
[profile-with-user-that-can-assume-role]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
aws_session_token=IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZVERYLONGSTRINGEXAMPLE

[profile dev]
region = us-east-1
output = json
role_arn = arn:aws:iam::123456789012:role/my-role-name
source_profile = profile-with-user-that-can-assume-role
role_session_name = my_session
```

For details on all assume role credential provider settings, see [Assume role credential provider](feature-assume-role-credentials.md) in this guide.

# Assuming a role with web identity or OpenID Connect to authenticate AWS SDKs and tools
<a name="access-assume-role-web"></a>

Assuming a role involves using a set of temporary security credentials to access AWS resources that you might not have access to otherwise. These temporary credentials consist of an access key ID, a secret access key, and a security token. To learn more about AWS Security Token Service (AWS STS) API requests, see [Actions](https://docs.aws.amazon.com/STS/latest/APIReference/API_Operations.html) in the *AWS Security Token Service API Reference*. 

To set up your SDK or tool to assume a role, you must first create or identify a specific *role* to assume. IAM roles are uniquely identified by a role Amazon Resource Name ([ARN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html)). Roles establish trust relationships with another entity. The trusted entity that uses the role might be a web identity provider or OpenID Connect(OIDC), or SAML federation. To learn more about IAM roles, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the *IAM User Guide*. 

After the IAM role is configured in your SDK, if that role is configured to trust your identity provider, you can further configure your SDK to assume that role in order to get temporary AWS credentials.

**Note**  
It is an AWS best practice to use Regional endpoints whenever possible and to configure your [AWS Region](feature-region.md). 

## Federate with web identity or OpenID Connect
<a name="webidentity"></a>

You can use the JSON Web Tokens (JWTs) from public identity providers, such as Login With Amazon, Facebook, Google to get temporary AWS credentials using `AssumeRoleWithWebIdentity`. Depending on how they are used, these JWTs may be called ID tokens or access tokens. You may also use JWTs issued from identity providers (IdPs) that are compatible with OIDC's discovery protocol, such as EntraId or PingFederate.

If you are using Amazon Elastic Kubernetes Service, this feature provides the ability to specify different IAM roles for each one of your service accounts in an Amazon EKS cluster. This Kubernetes feature distributes JWTs to your pods which are then used by this credential provider to obtain temporary AWS credentials. For more information on this Amazon EKS configuration, see [IAM roles for service accounts](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) in the **Amazon EKS User Guide**. However, for a simpler option, we recommend you use [Amazon EKS Pod Identities](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html) instead if your [SDK supports it](feature-container-credentials.md#feature-container-credentials-sdk-compat).

### Step 1: Set up an identity provider and IAM role
<a name="webidentity_step1"></a>

To configure federation with an external IdP, use an IAM identity provider to inform AWS about the external IdP and its configuration. This establishes *trust* between your AWS account and the external IdP. Before configuring the SDK to use the JSON Web Token (JWT) for authentication, you must first set up the identity provider (IdP) and the IAM role used to access it. To set these up, see [Creating a role for web identity or OpenID Connect Federation (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html) in the *IAM User Guide*.

### Step 2: Configure the SDK or tool
<a name="webidentity_step2"></a>

Configure the SDK or tool to use a JSON Web Token (JWT) from AWS STS for authentication. 

When you specify this in a profile, the SDK or tool automatically makes the corresponding AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API call for you. To retrieve and use temporary credentials using web identity federation, specify the following configuration values in the shared AWS `config` file. For more details on each of these settings, see the [Assume role credential provider settings](feature-assume-role-credentials.md#feature-assume-role-credentials-settings) section. 
+ `role_arn` - From the IAM role you created in Step 1
+ `web_identity_token_file` - From the external IdP
+ (Optional) `duration_seconds`
+ (Optional) `role_session_name` 

The following is an example of a shared `config` file configuration to assume a role with web identity:

```
[profile web-identity]
role_arn=arn:aws:iam::123456789012:role/my-role-name
web_identity_token_file=/path/to/a/token
```

**Note**  
For mobile applications, consider using Amazon Cognito. Amazon Cognito acts as an identity broker and does much of the federation work for you. However, the Amazon Cognito identity provider isn't included in the SDKs and tools core libraries like other identity providers. To access the Amazon Cognito API, include the Amazon Cognito service client in the build or libraries for your SDK or tool. For usage with AWS SDKs, see [Code Examples](https://docs.aws.amazon.com/cognito/latest/developerguide/service_code_examples.html) in the *Amazon Cognito Developer Guide*.

For details on all assume role credential provider settings, see [Assume role credential provider](feature-assume-role-credentials.md) in this guide.

# Using AWS access keys to authenticate AWS SDKs and tools
<a name="access-users"></a>

Using AWS access keys is an option for authentication when using AWS SDKs and tools.

## Use short-term credentials
<a name="credentials-temporary"></a>

 We recommend configuring your SDK or tool to use [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md) to use extended session duration options. 

However, to set up the SDK or tool's temporary credentials directly, see [Using short-term credentials to authenticate AWS SDKs and toolsShort-term credentials](access-temp-idc.md).

## Use long-term credentials
<a name="credentials-long-term"></a>

**Warning**  
To avoid security risks, don't use IAM users for authentication when developing purpose-built software or working with real data. Instead, use federation with an identity provider such as [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

### Manage access across AWS accounts
<a name="manage-access-accounts"></a>

As a security best practice, we recommend using AWS Organizations with IAM Identity Center to manage access across all your AWS accounts. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

You can create users in IAM Identity Center, use Microsoft Active Directory, use a SAML 2.0 identity provider (IdP), or individually federate your IdP to AWS accounts. Using one of these approaches, you can provide a single sign-on experience for your users. You can also enforce multi-factor authentication (MFA) and use temporary credentials for AWS account access. This differs from an IAM user, which is a long-term credential that can be shared and which might increase the security risk to your AWS resources.

### Create IAM users for sandbox environments only
<a name="create-iam-user-sandbox"></a>

If you're new to AWS, you might create a test IAM user and then use it to run tutorials and explore what AWS has to offer. It's okay to use this type of credential when you're learning, but we recommend that you avoid using it outside of a sandbox environment.

For the following use cases, it might make sense to get started with IAM users in AWS:
+ Getting started with your AWS SDK or tool and exploring AWS services in a sandbox environment.
+ Running scheduled scripts, jobs, and other automated processes that don't support a human-attended sign-in process as part of your learning.

If you're using IAM users outside of these use cases, then transition to IAM Identity Center or federate your identity provider to AWS accounts as soon as possible. For more information, see [Identity federation in AWS](https://aws.amazon.com/identity/federation/).

### Secure IAM user access keys
<a name="secure-iam-access-keys"></a>

You should rotate IAM user access keys regularly. Follow the guidance in [ Rotating access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_RotateAccessKey) in the *IAM User Guide*. If you believe that you have accidentally shared your IAM user access keys, then rotate your access keys.

IAM user access keys should be stored in the shared AWS `credentials` file on the local machine. Don't store the IAM user access keys in your code. Don't include configuration files that contain your IAM user access keys inside of any source code management software. External tools, such as the open source project [git-secrets](https://github.com/awslabs/git-secrets), can help you from inadvertently committing sensitive information to a Git repository. For more information, see [IAM Identities (users, user groups, and roles)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) in the *IAM User Guide*.

To set up an IAM user to get started, see [Using long-term credentials to authenticate AWS SDKs and tools](access-iam-users.md).

# Using short-term credentials to authenticate AWS SDKs and tools
<a name="access-temp-idc"></a>

 We recommend configuring your AWS SDK or tool to use [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md) with extended session duration options. However, you can copy and use temporary credentials that are available in the AWS access portal. New credentials will need to be copied when these expire. You can use the temporary credentials in a profile or use them as values for system properties and environment variables.

Best practice: Instead of manually managing access keys and a token in the credentials file, we recommend your application uses temporary credentials delivered from: 
+ An AWS compute service, such as running your application on Amazon Elastic Compute Cloud or in AWS Lambda.
+ Another option in the credential provider chain, such as [Using IAM Identity Center to authenticate AWS SDK and tools](access-sso.md).
+ Or use the [Process credential provider](feature-process-credentials.md) to retrieve temporary credentials.

**Set up a credentials file using short-term credentials retrieved from AWS access portal**

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 or tool 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 for [Manual credential refresh](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html#how-to-get-temp-credentials) to copy IAM role credentials from the AWS access portal.

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

   1. For step 7 in the linked instructions, select the **Manually add a profile to your AWS credentials file** option and copy the contents.

1. Paste the copied credentials into your local `credentials` file. The generated profile name is not needed if you are using the `default` profile. 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 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.

# Using long-term credentials to authenticate AWS SDKs and tools
<a name="access-iam-users"></a>

**Warning**  
To avoid security risks, don't use IAM users for authentication when developing purpose-built software or working with real data. Instead, use federation with an identity provider such as [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

If you use an IAM user to run your code, then the SDK or tool in your development environment authenticates by using long-term IAM user credentials in the shared AWS `credentials` file. Review the [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) topic and transition to IAM Identity Center or other temporary credentials as soon as possible.

## Important warnings and guidance for credentials
<a name="iam-warnings-and-guidelines"></a>

**Warnings for credentials**
+ ***Do NOT*** use your account's root credentials to access AWS resources. These credentials provide unrestricted account access and are difficult to revoke.
+ ***Do NOT*** put literal access keys or credential information in your application files. If you do, you create a risk of accidentally exposing your credentials if, for example, you upload the project to a public repository.
+ ***Do NOT*** include files that contain credentials in your project area.
+ Be aware that any credentials stored in the shared AWS `credentials` file are stored in plaintext.

**Additional guidance for securely managing credentials**

For a general discussion of how to securely manage AWS credentials, see [Best practices for managing AWS access keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) in the [AWS General Reference](https://docs.aws.amazon.com/general/latest/gr/). In addition to that discussion, consider the following:
+ Use [IAM roles for tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) for Amazon Elastic Container Service (Amazon ECS) tasks.
+ Use [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) for applications that are running on Amazon EC2 instances.

## Prerequisites: Create an AWS account
<a name="signup"></a>

To use an IAM user to access AWS services, you need an AWS account and AWS credentials.

1. **Create an account.**

   To create an AWS account, see [Getting started: Are you a first-time AWS user?](https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html) in the *AWS Account Management Reference Guide*.

1. **Create an administrative user.**

   Avoid using your root user account (the initial account you create) to access the management console and services. Instead, create an administrative user account, as explained in [Create an administrative user](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-set-up.html#create-an-admin) in the *IAM User Guide*.

   After you create the administrative user account and record the login details, **be sure to sign out of your root user account** and sign back in using the administrative account.

Neither of these accounts are appropriate for doing development on AWS or for running applications on AWS. As a best practice, you need to create users, permission sets, or service roles that are appropriate for these tasks. For more information, see [Apply least-privilege permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) in the *IAM User Guide*.

## Step 1: Create your IAM user
<a name="step1authIamUser"></a>
+ Create your IAM user by following the [Creating IAM users (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console) procedure in the *IAM User Guide*. When creating your IAM user:
  + We recommend you select **Provide user access to the AWS Management Console**. This allows you to view AWS services related to the code that you are running in a visual environment, such as checking AWS CloudTrail diagnostic logs or uploading files to Amazon Simple Storage Service, which is helpful when debugging your code.
  + For **Set permissions** - **Permission options**, select **Attach policies directly** for how you want to assign permissions to this user. 
    + Most "Getting Started" SDK tutorials use the Amazon S3 service as an example. To provide your application with full access to Amazon S3, select the `AmazonS3FullAccess` policy to attach to this user.
  + You can ignore the optional steps of that procedure regarding setting permission boundaries or tags. 

## Step 2: Get your access keys
<a name="stepGetKeys"></a>

1. In the navigation pane of the IAM console, select **Users** and then select the **User name** of the user that you created previously.

1. On the user's page, select the **Security credentials** page. Then, under **Access keys**, select **Create access key**.

1. For **Create access key Step 1**, choose either **Command Line Interface (CLI)** or **Local code**. Both options generate the same type of key to use with both the AWS CLI and the SDKs.

1. For **Create access key Step 2**, enter an optional tag and select **Next**.

1. For **Create access key Step 3**, select **Download .csv file** to save a `.csv` file with your IAM user's access key and secret access key. You need this information for later.
**Warning**  
Use appropriate security measures to keep these credentials safe.

1. Select **Done**. 

## Step 3: Update the shared `credentials` file
<a name="stepauthIamUser"></a>

1. Create or open the shared AWS `credentials` file. This file is `~/.aws/credentials` on Linux and macOS systems, and `%USERPROFILE%\.aws\credentials` on Windows. For more information, see [Location of Credentials Files](https://docs.aws.amazon.com/credref/latest/refdocs/file-location.html).

1. Add the following text to the shared `credentials` file. Replace the example ID value and example key value with the values in the `.csv` file that you downloaded earlier. 

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

   

1. Save the file.

The shared `credentials` file is the most common way to store credentials. These can also be set as environment variables, see [AWS access keys](feature-static-credentials.md) for environment variable names. This is a way to get you started, but we recommend you transition to IAM Identity Center or other temporary credentials as soon as possible. After you transition away from using long-term credentials, remember to delete these credentials from the shared `credentials` file.

# Using IAM roles to authenticate applications deployed to Amazon EC2
<a name="access-iam-roles-for-ec2"></a>

This example covers setting up an AWS Identity and Access Management role with Amazon S3 access to use in your application deployed to an Amazon Elastic Compute Cloud instance. 

In order to run your AWS SDK application on an Amazon Elastic Compute Cloud instance, create an IAM role, and then give your Amazon EC2 instance access to that role. For more information, see [IAM Roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) in the *Amazon EC2 User Guide* .

## Create an IAM role
<a name="createRoleForEc2"></a>

The AWS SDK application that you develop likely accesses at least one AWS service to perform actions. Create an IAM role that grants the required permissions necessary for your application to run.

 This procedure creates a role that grants read-only access to Amazon S3 as an example. Many of the AWS SDK guides have "getting started" tutorials that read from Amazon S3.

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, select **Roles**, then select **Create role**.

1. For **Select trusted entity**, under **Trusted entity type**, choose **AWS service**.

1. Under **Use case**, choose **Amazon EC2**, then select **Next**.

1. For **Add permissions**, select the checkbox for **Amazon S3 Read Only Access** from the policy list, then select **Next**. 

1. Enter a name for the role, then select **Create role**. *Remember this name because you'll need it when you create your Amazon EC2 instance.*

## Launch an Amazon EC2 instance and specify your IAM role
<a name="launchAndSpecify"></a>

You can create and launch an Amazon EC2 instance using your IAM role by doing the following:
+ Follow [Quickly launch an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html#liw-quickly-launch-instance) in the *Amazon EC2 User Guide*. However, prior to the final submission step, also do the following:
  + Under **Advanced details**, for **IAM Instance profile**, choose the role that you created in the previous step.

 With this IAM and Amazon EC2 setup, you can deploy your application to the Amazon EC2 instance and your application will have read access to the Amazon S3 service. 

## Connect to the EC2 instance
<a name="net-dg-hosm-connect"></a>

Connect to the Amazon EC2 instance so that you can transfer your application to it and then run the application. You'll need the file that contains the private portion of the key pair you used under **Key pair (login)** when you created your instance; that is, the PEM file.

You can do this by following the guidance for your instance type: [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) or [Connect to your Windows instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html). When you connect, do so in such a way that you can transfer files from your development machine to your instance. 

**Note**  
On Linux or macOS terminal, you can use the secure copy command to copy your application. To use `scp` with a key pair, you can use the following command: `scp -i path/to/key file/to/copy ec2-user@ec2-xx-xx-xxx-xxx.compute.amazonaws.com:~` .  
For more information for Windows, see [Transfer files to Windows instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instanceWindowsFileTransfer.html).

If you're using an AWS Toolkit, you can often also connect to the instance by using the Toolkit. For more information, see the specific user guide for the Toolkit you use.

## Run your application on the EC2 instance
<a name="net-dg-hosm-run-the-app"></a>

1. Copy your application files from your local drive to your Amazon EC2 instance.

1. Start the application and verify that it runs with the same results as on your development machine.

1. (Optional) Verify that the application uses the credentials provided by the IAM role.

   1. Sign in to the AWS Management Console and open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

   1. Select the instance.

   1. Choose **Actions**, **Security**, and then choose **Modify IAM role**.

   1.  For **IAM role**, detach the IAM role by choosing **No IAM Role**.

   1.  Choose **Update IAM role**.

   1. Run the application again and confirm that it returns an authorization error.

# Using the TIP plugin to access AWS services
<a name="access-tip"></a>

 Trusted identity propagation (TIP) is a feature of AWS IAM Identity Center that enables administrators of AWS services to grant permissions based on user attributes such as group associations. With trusted identity propagation, identity context is added to an IAM role to identify the user requesting access to AWS resources. This context is propagated to other AWS services. 

 Identity context comprises information that AWS services use to make authorization decisions when they receive access requests. This information includes metadata that identifies the requester (for example, an IAM Identity Center user), the AWS service to which access is requested (for example, Amazon Redshift), and the scope of access (for example, read only access). The receiving AWS service uses this context, and any permissions assigned to the user, to authorize access to its resources. For more information, see in the [Trusted identity propagation overview](https://docs.aws.amazon.com/singlesignon/latest/userguide/trustedidentitypropagation-overview.html) in the AWS IAM Identity Center User Guide. 

 The TIP plugin can be used with AWS services that support trusted identity propagation. As a reference use case, see [Configuring an Amazon Q Business application using AWS IAM Identity Center](https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/create-application.html) in the *Amazon Q Business User Guide*. 

**Note**  
 If you are using Amazon Q Business, see [Configuring an Amazon Q Business application using AWS IAM Identity Center](https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/create-application.html) for service-specific instructions. 

## Prerequisites for using the TIP plugin
<a name="prereq-tip"></a>

The following resources are required in order for the plugin to work: 

1. You must be using either the AWS SDK for Java or the AWS SDK for JavaScript. 

1. Verify that the service you are using supports the trusted identity propagation.

   See the **Enables trusted identity propagation through IAM Identity Center** column of the [AWS managed applications that integrate with IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/awsapps-that-work-with-identity-center.html) table in the *AWS IAM Identity Center User Guide*. 

1. Enable IAM Identity Center and trusted identity propagation.

   See [TIP prerequisites and considerations](https://docs.aws.amazon.com/singlesignon/latest/userguide/trustedidentitypropagation-overall-prerequisites.html) in the *AWS IAM Identity Center User Guide*. 

1. You must have an Identity-Center-integrated application. 

   See [AWS managed applications](https://docs.aws.amazon.com/singlesignon/latest/userguide/awsapps-quick-start-setting-up-identity-center-to-test-awsmanagedapps.html) or [Customer managed applications](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-trusted-identity-propagation-set-up-your-own-app-OAuth2.html) in the *AWS IAM Identity Center User Guide*. 

1. You must set up a trusted token issuer (TTI) and connect your service to IAM Identity Center. 

   See [Prerequisites for trusted token issuers](https://docs.aws.amazon.com/singlesignon/latest/userguide/using-apps-with-trusted-token-issuer.html#trusted-token-issuer-prerequisites) and [Tasks for setting up a trusted token issuer](https://docs.aws.amazon.com/singlesignon/latest/userguide/setuptrustedtokenissuer.html#setuptrustedtokenissuer-tasks) in the *AWS IAM Identity Center User Guide*.

## To use the TIP plugin in your code
<a name="using-tip"></a>

1. Create an instance of the trusted identity propagation plugin.

1. Create a service client instance for interacting with your AWS service and customize the service client by adding the trusted identity propagation plugin. 

The TIP plugin takes the following input parameters:
+ **`webTokenProvider`**: A function that the customer implements to obtain an OpenID token from their external identity provider. 
+ **`accessRoleArn`**: The IAM role ARN to be assumed by the plugin with the user's identity context to get the identity-enhanced credentials. 
+ **`applicationArn`**: The unique identifier string for the client or application. This value is an application ARN that has OAuth grants configured. 
+ **`ssoOidcClient`**: (Optional) An SSO OIDC client, such as [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/ssooidc/SsoOidcClient.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/ssooidc/SsoOidcClient.html) for Java or [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sso-oidc/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sso-oidc/) for JavaScript, with customer-defined configurations. If not provided, an OIDC client using `applicationRoleArn` will be instantiated and used. 
+  **`stsClient`**: (Optional) An AWS STS client with customer-defined configurations, used to assume `accessRoleArn` with the user's identity context. If not provided, an AWS STS client using `applicationRoleArn` will be instantiated and used. 
+ **`applicationRoleArn`**: (Optional) The IAM role ARN to be assumed with `AssumeRoleWithWebIdentity` so that the OIDC and AWS STS clients can be bootstrapped.
  + If not provided, **both** of the `ssoOidcClient` and `stsClient` parameters must be provided.
  + If provided, `applicationRoleArn` can't be the same value as the `accessRoleArn` parameter. `applicationRoleArn` is used to build the stsClient, which is used to assume accessRole. If the same role is used for both `applicationRole` and `accessRole`, it would mean using a role to assume itself (self-role assumption), which is discouraged by AWS. See the [announcement](https://aws.amazon.com/blogs/security/announcing-an-update-to-iam-role-trust-policy-behavior/) for more details.

### Considerations for `ssoOidcClient`, `stsClient`, and `applicationRoleArn` parameters
<a name="considerations-tip"></a>

When configuring the TIP plugin, consider the following permission requirements based on which parameters you provide:
+ If you are providing `ssoOidcClient` and `stsClient`:
  + Credentials on the `ssoOidcClient` should have `oauth:CreateTokenWithIAM` permission for calling identity center to get the identity center specific user context.
  + Credentials on `stsClient` should have `sts:AssumeRole`, and `sts:SetContext` permissions on `accessRole`. `accessRole` also needs to be configured with a trust relationship with the credentials on `stsClient`.
+ If you are providing `applicationRoleArn`:
  + `applicationRole` should have the `oauth:CreateTokenWithIAM`, `sts:AssumeRole` and `sts:SetContext` permissions on the required resources (IdC instance, `accessRole`) as it will be used to build OIDC and STS clients.
  + `applicationRole` should have a trust relationship with the identity provider that is used to generate the `webToken`, as the `webToken` will be used to assume the applicationRole via the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) call by the plugin.

**Example ApplicationRole configuration:**

Trust Policy with Web token provider:

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::ACCOUNT_ID:oidc-provider/IDENTITY_PROVIDER_URL"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "IDENTITY_PROVIDER_URL:aud": "CLIENT_ID_TO_BE_TRUSTED"
                }
            }
        }
    ]
}
```

Permission Policy:

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole",
                "sts:SetContext"
            ],
            "Resource": [
                "accessRoleArn"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso-oauth:CreateTokenWithIAM"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

## Code examples using TIP
<a name="tip-code-example"></a>

The examples below show how to implement the TIP plugin in your code using the AWS SDK for Java or the AWS SDK for JavaScript.

------
#### [ Java ]

To use the TIP plugin in your AWS SDK for Java project, you need to declare it as a dependency in your project's `pom.xml` file. 

```
<dependency>
<groupId>software.amazon.awsidentity.trustedIdentityPropagation</groupId>
<artifactId>aws-sdk-java-trustedIdentityPropagation-java-plugin</artifactId>
   <version>2.0.0</version>
</dependency>
```

In your source code, include the required package statement for `software.amazon.awssdk.trustedidentitypropagation`. 

The following examples show two ways to create an instance of the trusted identity propagation plugin and add it to a service client. Both examples use Amazon S3 as the service and utilize `S3AccessGrantsPlugin` to manage user specific permissions, but can be applied to any AWS service that supports trusted identity propagation (TIP). 

**Note**  
For these examples, you need to setup the user specific permissions from S3 Access Grants. Refer to the [S3 Access Grants documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html) for more details.

**Option 1: Build and pass OIDC and STS clients**

```
SsoOidcClient oidcClient = SsoOidcClient.builder()
    .region(Region.US_EAST_1)
    .credentialsProvider(credentialsProvider).build();

StsClient stsClient = StsClient.builder()
    .region(Region.US_EAST_1)
    .credentialsProvider(credentialsProvider).build();

TrustedIdentityPropagationPlugin trustedIdentityPropagationPlugin = TrustedIdentityPropagationPlugin.builder()
        .webTokenProvider(() -> webToken)
        .applicationArn(idcApplicationArn)
        .accessRoleArn(accessRoleArn)
        .ssoOidcClient(oidcClient)
        .stsClient(stsClient)
        .build();

S3AccessGrantsPlugin accessGrantsPlugin = S3AccessGrantsPlugin.builder()
        .build();

S3Client s3Client =
        S3Client.builder().region(Region.US_EAST_1)
                .crossRegionAccessEnabled(true)
                .addPlugin(trustedIdentityPropagationPlugin)
                .addPlugin(accessGrantsPlugin)
                .build();

final var resp = s3Client.getObject(GetObjectRequest.builder()
        .key("path/to/object/fileName")
        .bucket("bucketName")
        .build());
```

**Option 2: Pass applicationRoleArn and defer client creation to the plugin**

```
TrustedIdentityPropagationPlugin trustedIdentityPropagationPlugin = TrustedIdentityPropagationPlugin.builder()
        .webTokenProvider(() -> webToken)
        .applicationArn(idcApplicationArn)
        .accessRoleArn(accessRoleArn)
        .applicationRoleArn(applicationRoleArn)
        .build();

S3AccessGrantsPlugin accessGrantsPlugin = S3AccessGrantsPlugin.builder()
        .build();

S3Client s3Client =
        S3Client.builder().region(Region.US_EAST_1)
                .crossRegionAccessEnabled(true)
                .addPlugin(trustedIdentityPropagationPlugin)
                .addPlugin(accessGrantsPlugin)
                .build();

final var resp = s3Client.getObject(GetObjectRequest.builder()
        .key("path/to/object/fileName")
        .bucket("bucketName")
        .build());
```

For additional details and source, see [ trusted-identity-propagation-java](https://github.com/aws-sdk-plugin/trusted-identity-propagation-java) on GitHub.

------
#### [ JavaScript ]

Run the following command to install the TIP authentication plugin package in your AWS SDK for JavaScript project: 

```
$  npm i @aws-sdk-extension/trusted-identity-propagation
```

The final `package.json` should include a dependency similar to the following: 

```
  "dependencies": {
"@aws-sdk-extension/trusted-identity-propagation": "^2.0.0"
  },
```

 In your source code, import the required `TrustedIdentityPropagationExtension` dependency. 

 The following examples show two ways to create an instance of the trusted identity propagation plugin and add it to a service client. Both examples use Amazon S3 as the service and utilize Amazon S3 Access Grants to manage user specific permissions, but can be applied to any AWS service that supports trusted identity propagation (TIP). 

**Note**  
For these examples, you need to setup the user specific permissions from Amazon S3 Access Grants, refer to the [Amazon S3 Access Grants documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html) for more details.

**Option 1: Build and pass OIDC and STS clients**

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { S3ControlClient, GetDataAccessCommand } from "@aws-sdk/client-s3-control";
import { TrustedIdentityPropagationExtension } from "@aws-sdk-extension/trusted-identity-propagation";

const s3ControlClient = new S3ControlClient({
    region: "us-east-1",
    extensions: [
        TrustedIdentityPropagationExtension.create({
            webTokenProvider: async () => {
                return 'ID_TOKEN_FROM_YOUR_IDENTITY_PROVIDER';
            },
            ssoOidcClient: customOidcClient,
            stsClient: customStsClient,
            accessRoleArn: accessRoleArn,
            applicationArn: applicationArn,
        }),
    ],
});

const getDataAccessParams = {
  Target: "S3_URI_PATH",
  Permission: "READ",
  AccountId: ACCOUNT_ID,
  InstanceArn: S3_ACCESS_GRANTS_ARN,
  TargetType: "Object",
};

try {
  const command = new GetDataAccessCommand(getDataAccessParams);
  const response = await s3ControlClient.send(command);

  const credentials = response.Credentials;

  // Create a new S3 client with the temporary credentials
  const temporaryS3Client = new S3Client({
    region: "us-east-1",
    credentials: {
      accessKeyId: credentials.AccessKeyId,
      secretAccessKey: credentials.SecretAccessKey,
      sessionToken: credentials.SessionToken,
    },
  });

  // Use the temporary S3 client to perform the operation
  const s3Params = {
    Bucket: "BUCKET_NAME",
    Key: "S3_OBJECT_KEY",
  };
  const getObjectCommand = new GetObjectCommand(s3Params);
  const s3Object = await temporaryS3Client.send(getObjectCommand);

  const fileContent = await s3Object.Body.transformToString();

  // Process the S3 object data
  console.log("Successfully retrieved S3 object:", fileContent);
} catch (error) {
  console.error("Error accessing S3 data:", error);
}
```

**Option 2: Pass applicationRoleArn and defer client creation to the plugin**

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { S3ControlClient, GetDataAccessCommand } from "@aws-sdk/client-s3-control";
import { TrustedIdentityPropagationExtension } from "@aws-sdk-extension/trusted-identity-propagation";

const s3ControlClient = new S3ControlClient({
    region: "us-east-1",
    extensions: [
        TrustedIdentityPropagationExtension.create({
            webTokenProvider: async () => {
                return 'ID_TOKEN_FROM_YOUR_IDENTITY_PROVIDER';
            },
            accessRoleArn: accessRoleArn,
            applicationRoleArn: applicationRoleArn,
            applicationArn: applicationArn,
        }),
    ],
});

// Same S3 AccessGrants workflow as Option 1
const getDataAccessParams = {
  Target: "S3_URI_PATH",
  Permission: "READ",
  AccountId: ACCOUNT_ID,
  InstanceArn: S3_ACCESS_GRANTS_ARN,
  TargetType: "Object",
};

try {
  const command = new GetDataAccessCommand(getDataAccessParams);
  const response = await s3ControlClient.send(command);

  const credentials = response.Credentials;

  const temporaryS3Client = new S3Client({
    region: "us-east-1",
    credentials: {
      accessKeyId: credentials.AccessKeyId,
      secretAccessKey: credentials.SecretAccessKey,
      sessionToken: credentials.SessionToken,
    },
  });

  const s3Params = {
    Bucket: "BUCKET_NAME",
    Key: "S3_OBJECT_KEY",
  };
  const getObjectCommand = new GetObjectCommand(s3Params);
  const s3Object = await temporaryS3Client.send(getObjectCommand);

  const fileContent = await s3Object.Body.transformToString();

  console.log("Successfully retrieved S3 object:", fileContent);
} catch (error) {
  console.error("Error accessing S3 data:", error);
}
```

For additional details and source, see [trusted-identity-propagation-js](https://github.com/aws-sdk-plugin/trusted-identity-propagation-js) on GitHub.

------