

# Authentication and access credentials for the AWS CLI
<a name="cli-chap-authentication"></a>

You must establish how the AWS CLI authenticates with AWS when you develop with AWS services. To configure credentials for programmatic access for the AWS CLI, choose one of the following options. The options are in order of recommendation.


****  

| Authentication type | Purpose | Instructions | 
| --- | --- | --- | 
|  AWS Management Console credentials  | **(Recommended)**Use short-term credentials by logging into the AWS CLI with your console credentials. Recommended if you use root, IAM users, or federation with IAM for AWS account access | [Login for AWS local development using console credentials](cli-configure-sign-in.md) | 
|  IAM Identity Center workforce users short-term credentials  | Use short-term credentials for an IAM Identity Center workforce user.Security best practice is to use AWS Organizations with IAM Identity Center. It combines short-term credentials with a user directory, such as the built-in IAM Identity Center directory or Active Directory. | [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md) | 
| IAM user short-term credentials | Use IAM user short-term credentials, which are more secure than long-term credentials. If your credentials are compromised, there is a limited time they can be used before they expire. | [Authenticating with short-term credentials for the AWS CLI](cli-authentication-short-term.md) | 
| IAM or IAM Identity Center users on an Amazon EC2 instance.  | Use Amazon EC2 instance metadata to query for temporary credentials using the role assigned to the Amazon EC2 instance. | [Using Amazon EC2 instance metadata as credentials in the AWS CLI](cli-configure-metadata.md) | 
| Assume roles for permissions | Pair another credential method and assume a role for temporary access to AWS services your user might not have access to. | [Using an IAM role in the AWS CLI](cli-configure-role.md) | 
| IAM user long-term credentials | (Not recommended) Use long-term credentials, which have no expiration. | [Authenticating using IAM user credentials for the AWS CLI](cli-authentication-user.md) | 
| External storage of IAM or IAM Identity Center workforce users   | (Not recommended) Pair another credential method but store credential values in a location outside of the AWS CLI. This method is only as secure as the external location the credentials are stored. | [Sourcing credentials with an external process in the AWS CLI](cli-configure-sourcing-external.md) | 

## Configuration and credential precedence
<a name="cli-chap-authentication-precedence"></a>

Credentials and configuration settings are located in multiple places, such as the system or user environment variables, local AWS configuration files, or explicitly declared on the command line as a parameter. Certain authentication take precedence over others. The AWS CLI authentication settings take precedence in the following order:

1. **[Command line options](cli-configure-options.md)** – Overrides settings in any other location, such as the `--region`, `--output`, and `--profile` parameters.

1. **[Environment variables](cli-configure-envvars.md)** – You can store values in your system's environment variables.

1. **[Assume role](cli-configure-role.md)** – Assume the permissions of an IAM role through configuration or the [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) command.

1. **[Assume role with web identity](cli-configure-role.md)** – Assume the permissions of an IAM role using web identity through configuration or the [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html) command.

1. **[AWS IAM Identity Center](cli-configure-files.md)** – The IAM Identity Center configuration settings stored in the `config` file are updated when you run the `aws configure sso` command. Credentials are then authenticated when you run the `aws sso login` command. The `config` file is located at `~/.aws/config` on Linux or macOS, or at `C:\Users\USERNAME\.aws\config` on Windows. 

1. **[Credentials file](cli-configure-files.md)** – The `credentials` and `config` file are updated when you run the command `aws configure`. The `credentials` file is located at `~/.aws/credentials` on Linux or macOS, or at `C:\Users\USERNAME\.aws\credentials` on Windows.

1. **[Custom process](cli-configure-sourcing-external.md)** – Get your credentials from an external source.

1. **[Configuration file](cli-configure-files.md)** – The `credentials` and `config` file are updated when you run the command `aws configure`. The `config` file is located at `~/.aws/config` on Linux or macOS, or at `C:\Users\USERNAME\.aws\config` on Windows.

1. **[Container credentials](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html)** – You can associate an IAM role with each of your Amazon Elastic Container Service (Amazon ECS) task definitions. Temporary credentials for that role are then available to that task's containers. For more information, see [IAM Roles for Tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) in the *Amazon Elastic Container Service Developer Guide*.

1. **[Amazon EC2 instance profile credentials](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)** – You can associate an IAM role with each of your Amazon Elastic Compute Cloud (Amazon EC2) instances. Temporary credentials for that role are then available to code running in the instance. The credentials are delivered through the Amazon EC2 metadata service. 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* and [Using Instance Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) in the *IAM User Guide*.

## Additional topics in this section
<a name="cli-chap-authentication-topics"></a>
+ [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md)
+ [Authenticating with short-term credentials for the AWS CLI](cli-authentication-short-term.md)
+ [Using an IAM role in the AWS CLI](cli-configure-role.md)
+ [Authenticating using IAM user credentials for the AWS CLI](cli-authentication-user.md)
+ [Using Amazon EC2 instance metadata as credentials in the AWS CLI](cli-configure-metadata.md)
+ [Sourcing credentials with an external process in the AWS CLI](cli-configure-sourcing-external.md)

# Login for AWS local development using console credentials
<a name="cli-configure-sign-in"></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, AWS 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 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 CLI will automatically refresh these credentials for up to 12 hours.

Once configured, your session can be used in the AWS CLI and other AWS SDKs and Tools.

**Topics**
+ [

## Prerequisites
](#cli-configure-sign-in-prerequisites)
+ [

## Log in to the AWS CLI with the `aws login` command.
](#cli-configure-sign-in-login-command)
+ [

## Run a command with your profile
](#cli-configure-sign-in-with-profile)
+ [

## Sign out of your session using the aws logout command
](#cli-configure-sign-in-sign-out)
+ [

## Troubleshooting
](#cli-configure-sign-in-troubleshooting)
+ [

## Related resources
](#cli-configure-sign-in-resources)

## Prerequisites
<a name="cli-configure-sign-in-prerequisites"></a>
+ Install the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md). A minimum version of 2.32.0 is required to use the `aws login` command.
+ Access to sign into the AWS Management Console as a root user, IAM user, or through federation with IAM. If you use IAM Identity Center, go to [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md) instead.
+ Ensure the IAM identity has the appropriate permissions. Attach the [SignInLocalDevelopmentAccess](https://docs.aws.amazon.com/signin/latest/userguide/security-iam-awsmanpol.html) managed policy to your IAM user, role, or group. If you sign in as a root user, no additional permissions are required.

## Log in to the AWS CLI with the `aws login` command.
<a name="cli-configure-sign-in-login-command"></a>

Run the `aws login` command to authenticate using your existing AWS Management Console credentials. If you have not previously configured a profile, you're prompted for additional information. To sign in or configure a profile follow the below steps.

1. In your preferred terminal, run the `aws login` command.

   ```
   $ aws login
   ```

   To sign in to a named profile or create a new one, use the `--profile` option.

   ```
   $ aws login --profile my-dev-profile
   ```
   + If this is a new profile or no AWS Region has been specified, the AWS CLI prompts you to provide a region.

     ```
     No AWS region has been configured. The AWS region is the geographic location of 
     your AWS resources. 
     
     If you've used AWS before and already have resources in your account, tell us 
     which region they were created in. If you haven't created resources in your account 
     before, you can pick the region closest to you: 
     https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html. 
     You are able to change the region in the CLI at any time with the command 
     `aws configure set region NEW_REGION`.
     
     AWS Region [us-east-1]:
     ```
   + If the device using the AWS CLI does not have a browser, you can use the `--remote` option to provide a url for you to open on a browser-enabled device.

     ```
     $ aws login --remote
     ```
**Note**  
You can control access to same-device (`aws login`) and cross-device (`aws login --remote`) authentication. Use the following resource ARNs in any relevant IAM policy.  
`arn:aws:signin:region:account-id:oauth2/public-client/localhost` — Use this ARN for same-device authentication with `aws login`.
`arn:aws:signin:region:account-id:oauth2/public-client/remote` — Use this ARN for cross-device authentication with `aws login --remote`.

1. The AWS CLI attempts to open your default browser for the sign in process of your AWS account.

   ```
   Attempting to open the login page for `us-east-1` in your default browser. 
   If the browser does not open, use the following URL to complete your login:
   https://signin.us-east-1.amazonaws.com/authorize?<abbreviated>
   
   If you cannot connect to this URL, make sure that you have specified a valid region.
   ```
   + If you used the `--remote` option, instructions to manually start the sign in process are displayed based on the type of authorization you are using. The URL displayed is a unique URL starting with: https://us-east-1.signin.amazonaws.com/authorize. Once you complete the browser log in, you will need to copy and paste the resulting authorization code back in the CLI.

     ```
     Browser will not be automatically opened.
     Please visit the following URL:
     https://region.signin.amazonaws.com/authorize?<abbreviated>
     
     Please enter the authorization code displayed in the browser:
     ```

1. In the browser, select your credentials to use from the displayed list and then return to your terminal.
   + If the profile you are configuring has a previously configured login session that does not match your new session, the AWS CLI prompts you to confirm that you are switching the session that corresponds to the existing profile.

     ```
     Profile signin is already configured to use session arn:aws:iam::0123456789012:user/ReadOnly. 
     Do you want to overwrite it to use arn:aws:iam::0123456789012:user/Admin instead? (y/n):.
     ```

1. A final message describes the completed profile configuration. You can now use this profile to request credentials. Use the `aws login` command to request and retrieve the credentials needed to run commands.

   The authentication token is cached to disk under the `.aws/login/cache` directory with a filename based on the resolved profile.

### Generated configuration file
<a name="cli-configure-sign-in-generated-config"></a>

These steps result in creating the `default` profile in the `config` file that looks like the following:

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

## Run a command with your profile
<a name="cli-configure-sign-in-with-profile"></a>

Once signed in, you can use your credentials to invoke AWS CLI commands with the associated profile. The following example calls the `get-caller-identity` command using the `default` profile:

```
$ aws sts get-caller-identity
```

To sign in to a specific session, use the `--profile` option.

```
$ aws sts get-caller-identity --profile my-dev-profile
```

The AWS CLI and SDKs will automatically refresh the cached credentials every 15 minutes as needed. The overall session will be valid for up to the set session duration of the IAM principal (maximum of 12 hours), after which you must run `aws login` again.

## Sign out of your session using the aws logout command
<a name="cli-configure-sign-in-sign-out"></a>

When you are done using your session, you can let your credentials expire, or run the `aws logout` command to delete your cached credentials. If no profile is specified on the command line or in the `AWS_PROFILE` environment variable, the command signs you out of your default profile. The following example signs you out of your default profile.

```
$ aws logout
```

To sign out of a specific session, use the `--profile` option.

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

To sign out of all profiles that use login credentials, use the `--all` option.

```
$ aws logout --all
```

### Cached Credentials
<a name="cli-configure-sign-in-sharing-login-creds"></a>

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

To store the short-term credentails cache in an alternative location, set the `AWS_LOGIN_CACHE_DIRECTORY` environment variable.

#### Sharing Login credentials as process credentials
<a name="cli-configure-sign-in-cached-credentials"></a>

Older versions of the AWS SDKs or other development tools may not support console credentials yet. As a workaround, you can configure the AWS CLI to serve as a process credentials provider. The CLI will continue to refresh the credentials as needed, while sharing them with tools configured to use the credential\$1process profile.

In this example, use the AWS CLI to login first for profile signin:

```
$ aws login --profile signin
```

Then, manually configure a profile with the credential\$1process option, which points back at the signin profile. Now you can configure SDKs or tools to use the process profile, which will invoke the CLI to share the credentials from the signin profile.

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

[profile process] 
credential_process = aws configure export-credentials --profile signin --format process
region = us-east-1
```

## Troubleshooting
<a name="cli-configure-sign-in-troubleshooting"></a>

This page contains recommendations for toubleshooting issues with logging in for AWS local development using console credentials for the AWS CLI.

**Note**  
To troubleshoot other issues you may come across using the AWS CLI, see [Troubleshooting errors for the AWS CLI](cli-chap-troubleshooting.md).

### ExpiredToken or AccessDeniedException errors after using "aws login"
<a name="expired-token-login-troubleshooting"></a>

When running an AWS CLI command after running `aws login` for a given profile, you may encounter an expired or invalid credentials error.

```
$ aws s3 ls

An error occurred (ExpiredToken) when calling the ListBuckets operation: The provided token has expired.
```

**Possible cause:** You have a mix of existing credentials and the new login credentials in that profile

Run `aws configure list` or `aws configure list --profile <profile name>` to print where the CLI is resolving credentials from for either the default or the given profile.

If the TYPE column is something other than login, this means that there is still a different type of credentials set in the target profile.

In this example, credentials are being resolved from the shared credentials file in your home directory, which has precedence over the login credentials.

```
$  aws configure list
NAME       : VALUE                    : TYPE             : LOCATION
profile    : <not set>                : None             : None
access_key : ****************MPLE     : shared-credentials-file :
secret_key : ****************EKEY     : shared-credentials-file :
region     : us-east-1                : config-file      : ~/.aws/config
```

To address this, manually remove any existing credentials from your config and credentials file for the target profile. Once you do so, you should see login credentials when running `aws configure list` again.

```
$  aws configure list
NAME       : VALUE                    : TYPE             : LOCATION
profile    : <not set>                : None             : None
access_key : ****************MPLE     : login            :
secret_key : ****************EKEY     : login            :
region     : us-east-1                : config-file      : ~/.aws/config
```

Alternatively using the `--debug` option will show where the CLI is resolving credentials from.

### Firewall blocking network access when running "aws login"
<a name="firewall-blocking-login-troubleshooting"></a>

When running `aws login` you may encounter a popup or message from your firewall software that prevents the AWS CLI from accessing your network

**Possible cause:** Your firewall or security software is preventing the AWS CLI from opening the port used to handle the OAuth callback.

To avoid this issue, use the `--remote` option instead. This will prompt you to copy and paste the authorization code instead of using the OAuth callback.

```
$ aws login --remote
```

## Related resources
<a name="cli-configure-sign-in-resources"></a>

Additional resources are as follows.
+ [Installing or updating to the latest version of the AWS CLI](getting-started-install.md)
+ [`aws login` in the AWS CLI version 2 Reference](https://docs.aws.amazon.com/cli/latest/reference/)
+ [`aws logout` in the AWS CLI version 2 Reference](https://docs.aws.amazon.com/cli/latest/reference/)

# Configuring IAM Identity Center authentication with the AWS CLI
<a name="cli-configure-sso"></a>

This topic provides instructions on how to configure the AWS CLI with AWS IAM Identity Center (IAM Identity Center) to retrieve credentials to run AWS CLI commands. There are primarily two ways to authenticate users with IAM Identity Center to get credentials to run AWS CLI commands through the `config` file: 
+ **(Recommended)** SSO token provider configuration.
+ Legacy non-refreshable configuration.

For information on using bearer auth, which uses no account ID and role, see [Setting up to use the AWS CLI with CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/set-up-cli.html) in the *Amazon CodeCatalyst User Guide*.

**Note**  
For a guided process of using IAM Identity Center with AWS CLI commands, see [Tutorial: Using IAM Identity Center to run Amazon S3 commands in the AWS CLI](cli-configure-sso-tutorial.md).

**Topics**
+ [Prerequisites](#cli-configure-sso-prereqs)
+ [Configure your profile with the `aws configure sso` wizard](#cli-configure-sso-configure)
+ [Configure only your `sso-session` section with `aws configure sso-session` wizard](#cli-configure-sso-session)
+ [Manual configuration using the `config` file](#cli-configure-sso-manual)
+ [Sign in to an IAM Identity Center session](#cli-configure-sso-login)
+ [Run a command with your IAM Identity Center profile](#cli-configure-sso-use)
+ [Sign out of your IAM Identity Center sessions](#cli-configure-sso-logout)
+ [Troubleshooting](#cli-configure-sso-tshoot)
+ [Related resources](#cli-configure-sso-resources)

## Prerequisites
<a name="cli-configure-sso-prereqs"></a>
+ Install the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md).
+ You must first have access to SSO authentication within IAM Identity Center. 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>

Follow the instructions in [Getting started](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) in the *AWS IAM Identity Center User Guide*. This process activates IAM Identity Center, creates an administrative user, and adds an appropriate least-privilege permission set.

**Note**  
Create a permission set that applies least-privilege permissions. We recommend using the predefined `PowerUserAccess` permission set, unless your employer has created a custom permission set for this purpose. 

Exit the portal and sign in again to see your AWS accounts, programmatic access details, and options for `Administrator` or `PowerUserAccess`. Select `PowerUserAccess` when working with the SDK.

### I already have access to AWS through a federated identity provider managed by my employer (such as Azure AD 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 your 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.

After gaining access to IAM Identity Center, gather your IAM Identity Center information by performing the following:

1. Gather your `SSO Start URL` and `SSO Region` values that you need to run `aws configure sso`

   1. In your AWS access portal, select the permission set you use for development, and select the **Access keys** link.

   1. In the **Get credentials** dialog box, choose the tab that matches your operating system. 

   1. Choose the **IAM Identity Center credentials** method to get the `SSO Start URL` and `SSO Region` values.

1. Alternatively, starting with version 2.22.0, you can use the Issuer URL instead of the Start URL. The Issuer URL is located in the AWS IAM Identity Center console in one of the following locations:
   + On the **Dashboard** page, the Issuer URL is in the settings summary.
   + On the **Settings** page, the Issuer URL is in the **Identity source** settings. 

1. For information on which scopes value to register, see [OAuth 2.0 Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*.

## Configure your profile with the `aws configure sso` wizard
<a name="cli-configure-sso-configure"></a>

**To configure an IAM Identity Center profile for your AWS CLI:**

1. In your preferred terminal, run the `aws configure sso` command.

------
#### [ (Recommended) IAM Identity Center ]

   Create a session name, provide your IAM Identity Center start URL or the issuer URL, the AWS Region that hosts the IAM Identity Center directory, and the registration scope.

   ```
   $ aws configure sso
   SSO session name (Recommended): my-sso
   SSO start URL [None]: https://my-sso-portal.awsapps.com/start
   SSO region [None]: us-east-1
   SSO registration scopes [None]: sso:account:access
   ```

   For dual-stack support, use the dual-stack SSO start URL:

   ```
   $ aws configure sso
   SSO session name (Recommended): my-sso
   SSO start URL [None]: https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
   SSO region [None]: us-east-1
   SSO registration scopes [None]: sso:account:access
   ```

   Proof Key for Code Exchange (PKCE) authorization is used by default for the AWS CLI starting with version **2.22.0** and must be used on devices with a browser. To continue to use Device authorization, append the `--use-device-code` option.

   ```
   $ aws configure sso --use-device-code
   ```

------
#### [ Legacy IAM Identity Center ]

   Skip the session name and provide your IAM Identity Center start URL and the AWS Region that hosts the Identity Center directory. 

   ```
   $ aws configure sso
   SSO session name (Recommended):
   SSO start URL [None]: https://my-sso-portal.awsapps.com/start
   SSO region [None]:us-east-1
   ```

   For dual-stack support:

   ```
   $ aws configure sso
   SSO session name (Recommended):
   SSO start URL [None]: https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
   SSO region [None]:us-east-1
   ```

------

1. The AWS CLI attempts to open your default browser for the sign in process of your IAM Identity Center account. This process may prompt you to allow the AWS CLI access to your data. Since the AWS CLI is built on top of the SDK for Python, permission messages may contain variations of the `botocore` name.
   + **If the AWS CLI cannot open the browser**, instructions to manually start the sign in process are displayed based on the type of authorization you are using. 

------
#### [ PKCE authorization ]

     Proof Key for Code Exchange (PKCE) authorization is used by default for the AWS CLI starting with version 2.22.0. The URL displayed is a unique URL starting with:
     + IPv4: *https://oidc.us-east-1.amazonaws.com/authorize*
     + Dual-stack: *https://oidc.us-east-1.api.aws/authorize*

     PKCE authorization URLs must be opened on the same device you're signing in to and must be used for a device with a browser.

     ```
     Attempting to automatically open the SSO authorization page in your 
     default browser.
     If the browser does not open or you wish to use a different device to 
     authorize the request, open the following URL:
     
     https://oidc.us-east-1.amazonaws.com/authorize?<abbreviated>
     ```

------
#### [ Device authorization ]

     The OAuth 2.0 device authorization is used by the AWS CLI for versions older than 2.22.0. You can enable this method on newer versions by using the `--use-device-code` option.

     Device authorization URLs do not need to be opened on the same device you're signing in to and can be used for a device with or without a browser. The endpoint format depends on your configuration:
     + IPv4: *https://device.sso.us-west-2.amazonaws.com/*
     + Dual-stack: *https://device.sso.us-west-2.api.aws/*

     ```
     If the browser does not open or you wish to use a different device to 
     authorize this request, open the following URL:
     https://device.sso.us-west-2.amazonaws.com/
     
     Then enter the code:
     QCFK-N451
     ```

------

1. Select the AWS account to use from the displayed list. If you are authorized to use only one account, the AWS CLI automatically selects that account and skips the prompt.

   ```
   There are 2 AWS accounts available to you.
   > DeveloperAccount, developer-account-admin@example.com (123456789011) 
     ProductionAccount, production-account-admin@example.com (123456789022)
   ```

1. Select the IAM role to use from the displayed list. If there is only one role available, the AWS CLI automatically selects that role and skips the prompt.

   ```
   Using the account ID 123456789011
   There are 2 roles available to you.
   > ReadOnly
     FullAccess
   ```

1. Specify the [default output format](cli-configure-files.md#cli-config-output), the [default AWS Region](cli-configure-files.md#cli-config-region) to send commands to, and a [name for the profile](cli-configure-files.md). If you specify `default` as the profile name, this profile becomes the default profile used. In the following example, the user enters a default Region, default output format, and the name of the profile.

   ```
   Default client Region [None]: us-west-2<ENTER>
   CLI default output format (json if not specified) [None]: json<ENTER>
   Profile name [123456789011_ReadOnly]: my-dev-profile<ENTER>
   ```

1. A final message describes the completed profile configuration. You can now use this profile to request credentials. Use the `aws sso login` command to request and retrieve the credentials needed to run commands. For instructions, see [Sign in to an IAM Identity Center session](#cli-configure-sso-login).

### Generated configuration file
<a name="cli-configure-sso-generated"></a>

These steps result in creating the `sso-session` section and named profile in the `config` file that looks like the following:

------
#### [ IAM Identity Center ]

```
[profile my-dev-profile]
sso_session = my-sso
sso_account_id = 123456789011
sso_role_name = readOnly
region = us-west-2
output = json

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_registration_scopes = sso:account:access
```

For dual-stack support:

```
[profile my-dev-profile]
sso_session = my-sso
sso_account_id = 123456789011
sso_role_name = readOnly
region = us-west-2
output = json

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
sso_registration_scopes = sso:account:access
```

------
#### [ Legacy IAM Identity Center ]

```
[profile my-dev-profile]
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-east-1
sso_account_id = 123456789011
sso_role_name = readOnly
region = us-west-2
output = json
```

For dual-stack support:

```
[profile my-dev-profile]
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
sso_region = us-east-1
sso_account_id = 123456789011
sso_role_name = readOnly
region = us-west-2
output = json
```

------

## Configure only your `sso-session` section with `aws configure sso-session` wizard
<a name="cli-configure-sso-session"></a>

**Note**  
This configuration is not compatible with the legacy IAM Identity Center.

The `aws configure sso-session` command updates the `sso-session` sections in the `~/.aws/config` file. Run the `aws configure sso-session` command and provide your IAM Identity Center start URL or issuer URL and the AWS Region that hosts the IAM Identity Center directory. 

```
$ aws configure sso-session
SSO session name: my-sso
SSO start URL [None]: https://my-sso-portal.awsapps.com/start
SSO region [None]: us-east-1
SSO registration scopes [None]: sso:account:access
```

For dual-stack support, use the dual-stack SSO start URL:

```
$ aws configure sso-session
SSO session name: my-sso
SSO start URL [None]: https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
SSO region [None]: us-east-1
SSO registration scopes [None]: sso:account:access
```

## Manual configuration using the `config` file
<a name="cli-configure-sso-manual"></a>

IAM Identity Center configuration information is stored in the `config` file and can be edited using a text editor. To manually add IAM Identity Center support to a named profile, you must add keys and values to the `config` file. 

### IAM Identity Center configuration file
<a name="cli-configure-sso-manual-config"></a>

The `sso-session` section of the `config` file is used to group configuration variables for acquiring SSO access tokens, which can then be used to acquire AWS credentials. The following settings are used:
+ **(Required)** `sso\$1start\$1url`
+ **(Required)** `sso\$1region`
+ `sso\$1account\$1id`
+ `sso\$1role\$1name`
+ `sso\$1registration\$1scopes`

You define an `sso-session` section and associate it to a profile. The `sso_region` and `sso_start_url` settings must be set within the `sso-session` section. Typically, `sso_account_id` and `sso_role_name` must be set in the `profile` section so that the SDK can request SSO credentials. 

The following example configures the SDK to request SSO credentials and supports automated token refresh: 

```
[profile dev]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://my-sso-portal.awsapps.com/start
```

For dual-stack support, use the dual-stack SSO start URL format:

```
[profile dev]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
```

This also allows `sso-session` configurations to be reused across multiple profiles: 

```
[profile dev]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[profile prod]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole2

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://my-sso-portal.awsapps.com/start
```

For dual-stack support, use the dual-stack SSO start URL format:

```
[profile dev]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[profile prod]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole2

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
```

However, `sso_account_id` and `sso_role_name` aren't required for all scenarios of SSO token configuration. If your application only uses AWS services that support bearer authentication, then traditional AWS credentials are not needed. Bearer authentication is an HTTP authentication scheme that uses security tokens called bearer tokens. In this scenario, `sso_account_id` and `sso_role_name` aren't required. See the individual guide for your AWS service to determine if it supports bearer token authorization.

Additionally, registration scopes can be configured as part of a `sso-session`. Scope is a mechanism in OAuth 2.0 to limit an application's access to a user's account. An application can request one or more scopes, and the access token issued to the application will be limited to the scopes granted. These scopes define the permissions requested to be authorized for the registered OIDC client and access tokens retrieved by the client. The following example sets `sso_registration_scopes` to provide access for listing accounts/roles: 

```
[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_registration_scopes = sso:account:access
```

For dual-stack support:

```
[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
sso_registration_scopes = sso:account:access
```

The authentication token is cached to disk under the `sso/cache` directory with a filename based on the session name. 

### Legacy IAM Identity Center configuration file
<a name="cli-configure-sso-manual-legacy"></a>

**Note**  
Automated token refresh isn't supported using the legacy non-refreshable configuration. We recommend using the SSO token configuration.

To manually add IAM Identity Center support to a named profile, you must add the following keys and values to the profile definition in the `config` file.
+ `sso\$1start\$1url`
+ `sso\$1region`
+ `sso\$1account\$1id`
+ `sso\$1role\$1name`

You can include any other keys and values that are valid in the `.aws/config` file. The following example is an IAM Identity Center profile:

```
[profile my-sso-profile]
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-west-2
sso_account_id = 111122223333
sso_role_name = SSOReadOnlyRole
region = us-west-2
output = json
```

For dual-stack support:

```
[profile my-sso-profile]
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
sso_region = us-west-2
sso_account_id = 111122223333
sso_role_name = SSOReadOnlyRole
region = us-west-2
output = json
```

To run commands, you must first [Sign in to an IAM Identity Center session](#cli-configure-sso-login) to request and retrieve your temporary credentials.

For more information on the `config` and `credentials` files, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md).

## Sign in to an IAM Identity Center session
<a name="cli-configure-sso-login"></a>

**Note**  
The sign in process may prompt you to allow the AWS CLI access to your data. Since the AWS CLI is built on top of the SDK for Python, permission messages may contain variations of the `botocore` name.

To retrieve and cache a set of IAM Identity Center credentials, run the following command for the AWS CLI to open your default browser and verify your IAM Identity Center log in. 

```
$ aws sso login --profile my-dev-profile
SSO authorization page has automatically been opened in your default browser. 
Follow the instructions in the browser to complete this authorization request.
Successfully logged into Start URL: https://my-sso-portal.awsapps.com/start
```

Your IAM Identity Center session credentials are cached and the AWS CLI uses them to securely retrieve AWS credentials for the IAM role specified in the profile. 

### If the AWS CLI can't open your browser
<a name="cli-configure-sso-login-browser"></a>

If the AWS CLI cannot automatically open your browser, instructions to manually start the sign in process are displayed based on the type of authorization you are using. 

------
#### [ PKCE authorization ]

Proof Key for Code Exchange (PKCE) authorization is used by default for the AWS CLI starting with version 2.22.0. The URL displayed is a unique URL starting with:
+ IPv4: *https://oidc.us-east-1.amazonaws.com/authorize*
+ Dual-stack: *https://oidc.us-east-1.api.aws/authorize*

PKCE authorization URLs must be opened on the same device you're signing in to and must be used for a device with a browser.

```
Attempting to automatically open the SSO authorization page in your 
default browser.
If the browser does not open or you wish to use a different device to 
authorize the request, open the following URL:

https://oidc.us-east-1.amazonaws.com/authorize?<abbreviated>
```

------
#### [ Device authorization ]

The OAuth 2.0 device authorization is used by the AWS CLI for versions older than 2.22.0. You can enable this method on newer versions by using the `--use-device-code` option.

Device authorization URLs do not need to be opened on the same device you're signing in to and can be used for a device with or without a browser.

```
If the browser does not open or you wish to use a different device to 
authorize this request, open the following URL:
https://device.sso.us-west-2.amazonaws.com/

Then enter the code:
QCFK-N451
```

------

You can also specify which `sso-session` profile to use when logging in using the `--sso-session` parameter of the `aws sso login` command. The `sso-session` option is not available for legacy IAM Identity Center.

```
$ aws sso login --sso-session my-dev-session
```

Starting with version 2.22.0, PKCE authorization is the default. To use device authorization for signing in, add the `--use-device-code` option.

```
$ aws sso login --profile my-dev-profile --use-device-code
```

The authentication token is cached to disk under the `~/.aws/sso/cache` directory with a filename based on the `sso_start_url`. 

## Run a command with your IAM Identity Center profile
<a name="cli-configure-sso-use"></a>

Once logged in, you can use your credentials to invoke AWS CLI commands with the associated named profile. The following example shows a command using a profile:

```
$ aws sts get-caller-identity --profile my-dev-profile
```

As long as you are signed in to IAM Identity Center and those cached credentials are not expired, the AWS CLI automatically renews expired AWS credentials when needed. However, if your IAM Identity Center credentials expire, you must explicitly renew them by logging in to your IAM Identity Center account again.

## Sign out of your IAM Identity Center sessions
<a name="cli-configure-sso-logout"></a>

When you are done using your IAM Identity Center profile, you can let your credentials expire or run the following command to delete your cached credentials.

```
$ aws sso logout
Successfully signed out of all SSO profiles.
```

## Troubleshooting
<a name="cli-configure-sso-tshoot"></a>

If you come across issues using the AWS CLI, see [Troubleshooting errors for the AWS CLI](cli-chap-troubleshooting.md) for troubleshooting steps.

## Related resources
<a name="cli-configure-sso-resources"></a>

Additional resources are as follows.
+ [AWS IAM Identity Center concepts for the AWS CLI](cli-configure-sso-concepts.md)
+ [Tutorial: Using IAM Identity Center to run Amazon S3 commands in the AWS CLI](cli-configure-sso-tutorial.md)
+ [Installing or updating to the latest version of the AWS CLI](getting-started-install.md)
+ [Configuration and credential file settings in the AWS CLI](cli-configure-files.md)
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/login.html](https://docs.aws.amazon.com/cli/latest/reference/sso/login.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html](https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html) in the *AWS CLI version 2 Reference*
+ [Setting up to use the AWS CLI with CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/set-up-cli.html) in the *Amazon CodeCatalyst User Guide*
+ [OAuth 2.0 Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*
+ [Getting started tutorials](https://docs.aws.amazon.com/singlesignon/latest/userguide/tutorials.html) in the *IAM Identity Center User Guide*

# AWS IAM Identity Center concepts for the AWS CLI
<a name="cli-configure-sso-concepts"></a>

This topic describes the key concepts of AWS IAM Identity Center (IAM Identity Center). IAM Identity Center is a cloud-based IAM service that simplifies user access management across multiple AWS accounts, applications, SDKs, and tools by integrating with existing identity providers (IdP). It enables secure single sign-on, permission management, and auditing through a centralized user portal, streamlining identity and access governance for organizations.

**Topics**
+ [

## What is IAM Identity Center
](#cli-configure-sso-concepts-what)
+ [

## Terms
](#cli-configure-sso-terms)
+ [

## How IAM Identity Center works
](#cli-configure-sso-concepts-process)
+ [

## Additional resources
](#cli-configure-sso-concepts-resources)

## What is IAM Identity Center
<a name="cli-configure-sso-concepts-what"></a>

IAM Identity Center is a cloud-based identity and access management (IAM) service that enables you to centrally manage access to multiple AWS accounts and business applications.

It provides a user portal where authorized users can access the AWS accounts and applications they've been granted permission to, using their existing corporate credentials. This allows organizations to enforce consistent security policies and streamline user access management.

Regardless of which IdP you use, IAM Identity Center abstracts those distinctions away. For example, you can connect Microsoft Azure AD as described in the blog article [The Next Evolution in IAM Identity Center](https://aws.amazon.com/blogs/aws/the-next-evolution-in-aws-single-sign-on/).

**Note**  
For information on using bearer auth, which uses no account ID and role, see [Setting up to use the AWS CLI with CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/set-up-cli.html) in the *Amazon CodeCatalyst User Guide*.

## Terms
<a name="cli-configure-sso-terms"></a>

Common terms when using IAM Identity Center are as follows:

**Identity Provider (IdP)**  
An identity management system such as IAM Identity Center, Microsoft Azure AD, Okta, or your own corporate directory service.

**AWS IAM Identity Center**  
IAM Identity Center is the AWS owned IdP service. Formerly known as AWS Single Sign-On, SDKs and tools keep the `sso` API namespaces for backward compatibility. 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*.

**AWS access portal URL, SSO start URL, Start URL**  
Your organization's unique IAM Identity Center URL to access your authorized AWS accounts, services, and resources.

**Issuer URL**  
Your organization's unique IAM Identity Center issuer URL for programmatic access for your authorized AWS accounts, services, and resources. Starting with version 2.22.0 of the AWS CLI, issuer URL can be used interchangeably with the start URL.

**Federation**  
The process of establishing trust between IAM Identity Center and an identity provider to enable single sign-on (SSO).

**AWS accounts**  
The AWS accounts that you provide users access to through AWS IAM Identity Center.

**Permission sets, AWS credentials, credentials, sigv4 credentials**  
Predefined collections of permissions that can be assigned to users or groups to grant access to AWS services.

**Registration scopes, access scopes, scopes**  
Scopes are a mechanism in OAuth 2.0 to limit an application's access to a user's account. An application can request one or more scopes, and the access token issued to the application is limited to the scopes granted. For information on scopes, see [Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*.

**Tokens, refresh token, access token**  
Tokens are temporary security credentials that are issued to you upon authentication. These tokens contain information about your identity and the permissions you've been granted.  
When you access an AWS resource or application through the IAM Identity Center portal, your token is presented to AWS for authentication and authorization. This allows AWS to verify your identity and ensure you have the necessary permissions to perform your requested actions.   
The authentication token is cached to disk under the `~/.aws/sso/cache` directory with a JSON filename based on the session name.

**Session**  
An IAM Identity Center session refers to the period of time that a user is authenticated and authorized to access AWS resources or applications. When a user signs in to the IAM Identity Center portal, a session is established, and the user's token is valid for a specified duration. For more information on setting session durations, see [Set session duration](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html) in the *AWS IAM Identity Center User Guide*.  
During the session, you can navigate between different AWS accounts and applications without having to re-authenticate, as long as their session remains active. When the session expires, sign in again to renew your access.  
IAM Identity Center sessions help to provide a seamless user experience while also enforcing security best practices by limiting the validity of user access credentials.

**Authorization code grant with PKCE, PKCE, Proof Key for Code Exchange**  
Starting with version 2.22.0, Proof Key for Code Exchange (PKCE) is an OAuth 2.0 authentication grant flow for devices with a browser. PKCE is a simple and safe way to authenticate and obtain consent to access your AWS resources from desktops and mobile devices with web browsers. This is the default authorization behavior. For more information on PKCE, see [Authorization Code Grant with PKCE](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#auth-code-grant-pkce) in the *AWS IAM Identity Center User Guide*.

**Device authorization grant**  
An OAuth 2.0 authentication grant flow for devices with or without a web browser. For more information on setting session durations, see [Device Authorization Grant](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#device-auth-grant) in the *AWS IAM Identity Center User Guide*.

## How IAM Identity Center works
<a name="cli-configure-sso-concepts-process"></a>

IAM Identity Center integrates with your organization's identity provider, such as IAM Identity Center, Microsoft Azure AD, or Okta. Users authenticate against this identity provider, and IAM Identity Center then maps those identities to the appropriate permissions and access within your AWS environment.

The following IAM Identity Center workflow assumes you have already configured your AWS CLI to use IAM Identity Center:

1. In your preferred terminal, run the `aws sso login` command.

1. Sign in to your AWS access portal to start a new session. 
   + When you start a new session, you receive a refresh token and access token that is cached.
   + If you already have an active session, the existing session is reused and expires when the existing session expires.

1. Based on the profile you've set up in your `config` file, IAM Identity Center assumes the appropriate permission sets, granting access to the relevant AWS accounts and applications. 

1. The AWS CLI, SDKs, and Tools use your assumed IAM role to make calls to AWS services such as creating Amazon S3 buckets until that session expires.

1. The access token from IAM Identity Center is checked hourly and is automatically refreshed using the refresh token.
   + If the access token is expired, the SDK or tool uses the refresh token to get a new access token. These tokens' session durations are then compared, and if the refresh token is not expired IAM Identity Center provides a new access token.
   + If the refresh token has expired, then no new access tokens are provided and your session has ended.

1. Sessions end after refresh tokens expire, or when you manually log out using the `aws sso logout` command. Cached credentials are removed. To continue accessing services using IAM Identity Center, you must start a new session using the the `aws sso login` command.

## Additional resources
<a name="cli-configure-sso-concepts-resources"></a>

Additional resources are as follows.
+ [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md)
+ [Tutorial: Using IAM Identity Center to run Amazon S3 commands in the AWS CLI](cli-configure-sso-tutorial.md)
+ [Installing or updating to the latest version of the AWS CLI](getting-started-install.md)
+ [Configuration and credential file settings in the AWS CLI](cli-configure-files.md)
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/login.html](https://docs.aws.amazon.com/cli/latest/reference/sso/login.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html](https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html) in the *AWS CLI version 2 Reference*
+ [Setting up to use the AWS CLI with CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/set-up-cli.html) in the *Amazon CodeCatalyst User Guide*
+ [IAM Identity Center rename](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed) in the *AWS IAM Identity Center User Guide*
+ [OAuth 2.0 Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*
+ [Set session duration](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html) in the *AWS IAM Identity Center User Guide*
+ [Getting started tutorials](https://docs.aws.amazon.com/singlesignon/latest/userguide/tutorials.html) in the *IAM Identity Center User Guide*

# Tutorial: Using IAM Identity Center to run Amazon S3 commands in the AWS CLI
<a name="cli-configure-sso-tutorial"></a>

This topic describes how to configure the AWS CLI to authenticate users with current AWS IAM Identity Center (IAM Identity Center) to retrieve credentials to run AWS Command Line Interface (AWS CLI) commands for Amazon Simple Storage Service (Amazon S3). 

**Topics**
+ [

## Step 1: Authentication in IAM Identity Center
](#cli-configure-sso-tutorial-authentication)
+ [

## Step 2: Gather your IAM Identity Center information
](#cli-configure-sso-tutorial-gather)
+ [

## Step 3: Create Amazon S3 buckets
](#cli-configure-sso-tutorial-buckets)
+ [

## Step 4: Install the AWS CLI
](#cli-configure-sso-tutorial-install)
+ [

## Step 5: Configure your AWS CLI profile
](#cli-configure-sso-tutorial-configure)
+ [

## Step 6: Log in to IAM Identity Center
](#cli-configure-sso-tutorial-login.title)
+ [

## Step 7: Run Amazon S3 commands
](#cli-configure-sso-tutorial-commands)
+ [

## Step 8: Log out of IAM Identity Center
](#cli-configure-sso-tutorial-logout)
+ [

## Step 9: Clean up resources
](#cli-configure-sso-tutorial-cleanup)
+ [

## Troubleshooting
](#cli-configure-sso-tutorial-tshoot)
+ [

## Additional resources
](#cli-configure-sso-tutorial-resources.title)

## Step 1: Authentication in IAM Identity Center
<a name="cli-configure-sso-tutorial-authentication"></a>

Gain access to SSO authentication within IAM Identity Center. 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>

Follow the instructions in [Getting started](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) in the *AWS IAM Identity Center User Guide*. This process activates IAM Identity Center, creates an administrative user, and adds an appropriate least-privilege permission set.

**Note**  
Create a permission set that applies least-privilege permissions. We recommend using the predefined `PowerUserAccess` permission set, unless your employer has created a custom permission set for this purpose. 

Exit the portal and sign in again to see your AWS accounts, programmatic access details, and options for `Administrator` or `PowerUserAccess`. Select `PowerUserAccess` when working with the SDK.

### I already have access to AWS through a federated identity provider managed by my employer (such as Azure AD 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 your 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: Gather your IAM Identity Center information
<a name="cli-configure-sso-tutorial-gather"></a>

After gaining access to AWS, gather your IAM Identity Center information by performing the following:

1. Gather your `SSO Start URL` and `SSO Region` values that you need to run `aws configure sso`

   1. In your AWS access portal, select the permission set you use for development, and select the **Access keys** link.

   1. In the **Get credentials** dialog box, choose the tab that matches your operating system. 

   1. Choose the **IAM Identity Center credentials** method to get the `SSO Start URL` and `SSO Region` values.

1. Alternatively, starting with version 2.22.0, you can use the new Issuer URL instead of the Start URL. The Issuer URL is located in the AWS IAM Identity Center console in one of the following locations:
   + On the **Dashboard** page, the Issuer URL is in the settings summary.
   + On the **Settings** page, the Issuer URL is in the **Identity source** settings. 

1. For information on which scopes value to register, see [OAuth 2.0 Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*.

## Step 3: Create Amazon S3 buckets
<a name="cli-configure-sso-tutorial-buckets"></a>

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

For this tutorial, create a few buckets to be later retrieved in a list.

## Step 4: Install the AWS CLI
<a name="cli-configure-sso-tutorial-install"></a>

Install the AWS CLI following the instructions for your operating system. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md).

Once installed, you can verify the installation by opening your preferred terminal and running the following command. This should display your installed version of the AWS CLI. 

```
$ aws --version
```

## Step 5: Configure your AWS CLI profile
<a name="cli-configure-sso-tutorial-configure"></a>

Configure your profile using one of the following methods

### Configure your profile with the `aws configure sso` wizard
<a name="li-configure-sso-tutorial-configure-wizard"></a>

The `sso-session` section of the `config` file is used to group configuration variables for acquiring SSO access tokens, which can then be used to acquire AWS credentials. The following settings are used:
+ **(Required)** `sso\$1start\$1url`
+ **(Required)** `sso\$1region`
+ `sso\$1account\$1id`
+ `sso\$1role\$1name`
+ `sso\$1registration\$1scopes`

You define an `sso-session` section and associate it to a profile. The `sso_region` and `sso_start_url` settings must be set within the `sso-session` section. Typically, `sso_account_id` and `sso_role_name` must be set in the `profile` section so that the SDK can request SSO credentials. 

The following example configures the SDK to request SSO credentials and supports automated token refresh: 

```
$ aws configure sso
SSO session name (Recommended): my-sso
SSO start URL [None]: https://my-sso-portal.awsapps.com/start
SSO region [None]: us-east-1
SSO registration scopes [None]: sso:account:access
```

For dual-stack support, you can use the dual-stack SSO start URL format:

```
$ aws configure sso
SSO session name (Recommended): my-sso
SSO start URL [None]: https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
SSO region [None]: us-east-1
SSO registration scopes [None]: sso:account:access
```

Proof Key for Code Exchange (PKCE) authorization is used by default for the AWS CLI starting with version 2.22.0 and must be used on devices with a browser. To continue to use Device authorization, append the `--use-device-code` option.

```
$ aws configure sso --use-device-code
```

### Manual configuration using the `config` file
<a name="cli-configure-sso-tutorial-configure-manual"></a>

The `sso-session` section of the `config` file is used to group configuration variables for acquiring SSO access tokens, which can then be used to acquire AWS credentials. The following settings are used:
+ **(Required)** `sso\$1start\$1url`
+ **(Required)** `sso\$1region`
+ `sso\$1account\$1id`
+ `sso\$1role\$1name`
+ `sso\$1registration\$1scopes`

You define an `sso-session` section and associate it to a profile. `sso_region` and `sso_start_url` must be set within the `sso-session` section. Typically, `sso_account_id` and `sso_role_name` must be set in the `profile` section so that the SDK can request SSO credentials. 

The following example configures the SDK to request SSO credentials and supports automated token refresh: 

```
[profile my-dev-profile]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_registration_scopes = sso:account:access
```

For dual-stack support, use the dual-stack SSO start URL format:

```
[profile my-dev-profile]
sso_session = my-sso
sso_account_id = 111122223333
sso_role_name = SampleRole

[sso-session my-sso]
sso_region = us-east-1
sso_start_url = https://ssoins-1234567890abcdef.portal.us-east-1.app.aws
sso_registration_scopes = sso:account:access
```

The authentication token is cached to disk under the `~/.aws/sso/cache` directory with a filename based on the session name. 

## Step 6: Log in to IAM Identity Center
<a name="cli-configure-sso-tutorial-login.title"></a>

**Note**  
The sign in process may prompt you to allow the AWS CLI access to your data. Since the AWS CLI is built on top of the SDK for Python, permission messages may contain variations of the `botocore` name.

To retrieve and cache your IAM Identity Center credentials, run the following command for the AWS CLI to open your default browser and verify your IAM Identity Center log in.

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

Starting with version 2.22.0, PKCE authorization is the default. To use device authorization for signing in, add the `--use-device-code` option.

```
$ aws sso login --profile my-dev-profile --use-device-code
```

## Step 7: Run Amazon S3 commands
<a name="cli-configure-sso-tutorial-commands"></a>

To list the buckets you created earlier, use the [https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html](https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html) command. The following example lists all of your Amazon S3 buckets.

```
$ aws s3 ls
2018-12-11 17:08:50 my-bucket
2018-12-14 14:55:44 my-bucket2
```

## Step 8: Log out of IAM Identity Center
<a name="cli-configure-sso-tutorial-logout"></a>

When you are done using your IAM Identity Center profile, run the following command to delete your cached credentials.

```
$ aws sso logout
Successfully signed out of all SSO profiles.
```

## Step 9: Clean up resources
<a name="cli-configure-sso-tutorial-cleanup"></a>

After you're done with this tutorial, clean up any resources you created during this tutorial that you no longer need, including Amazon S3 buckets.

## Troubleshooting
<a name="cli-configure-sso-tutorial-tshoot"></a>

If you come across issues using the AWS CLI, see [Troubleshooting errors for the AWS CLI](cli-chap-troubleshooting.md) for common troubleshooting steps.

## Additional resources
<a name="cli-configure-sso-tutorial-resources.title"></a>

Additional resources are as follows.
+ [AWS IAM Identity Center concepts for the AWS CLI](cli-configure-sso-concepts.md)
+ [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md)
+ [Installing or updating to the latest version of the AWS CLI](getting-started-install.md)
+ [Configuration and credential file settings in the AWS CLI](cli-configure-files.md)
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html](https://docs.aws.amazon.com/cli/latest/reference/configure/sso-session.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/login.html](https://docs.aws.amazon.com/cli/latest/reference/sso/login.html) in the *AWS CLI version 2 Reference*
+ [https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html](https://docs.aws.amazon.com/cli/latest/reference/sso/logout.html) in the *AWS CLI version 2 Reference*
+ [Setting up to use the AWS CLI with CodeCatalyst](https://docs.aws.amazon.com/codecatalyst/latest/userguide/set-up-cli.html) in the *Amazon CodeCatalyst User Guide*
+ [OAuth 2.0 Access scopes](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-saml2-oauth2.html#oidc-concept) in the *IAM Identity Center User Guide*
+ [Getting started tutorials](https://docs.aws.amazon.com/singlesignon/latest/userguide/tutorials.html) in the *IAM Identity Center User Guide*

# Authenticating with short-term credentials for the AWS CLI
<a name="cli-authentication-short-term"></a>

We recommend configuring your SDK or tool to use [IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) 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.

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

1. Follow [these instructions](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html) to copy IAM role credentials from the AWS access portal.

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

   1. For step 4, select the **Add a profile to your AWS credentials file** option and copy the contents. 

1. Create or open the shared `credentials` file. This file is `~/.aws/credentials` on Linux and macOS systems, and `%USERPROFILE%\.aws\credentials` on Windows. For more information, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md). 

1. Add the following text to the shared `credentials` file. Replace the sample values with the credentials you copied. 

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

1. Add your preferred default region and format to the shared `config` file. 

   ```
   [default]
   region=us-west-2
   output=json
   
   [profile user1]
   region=us-east-1
   output=text
   ```

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 2a determine [how long the temporary credentials are valid](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtosessionduration.html). The maximum duration is twelve hours.

Repeat these steps each time your credentials expire.

# Using an IAM role in the AWS CLI
<a name="cli-configure-role"></a>

An [AWS Identity and Access Management (IAM) role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) is an authorization tool that lets a user gain additional (or different) permissions, or get permissions to perform actions in a different AWS account. 

**Topics**
+ [

## Prerequisites
](#cli-role-prereqs)
+ [

## Overview of using IAM roles
](#cli-role-overview)
+ [

## Configuring and using a role
](#cli-role-prepare)
+ [

## Using multi-factor authentication
](#cli-configure-role-mfa)
+ [

## Cross-account roles and external ID
](#cli-configure-role-xaccount)
+ [

## Specifying a role session name for easier auditing
](#cli-configure-role-session-name)
+ [

## Assume role with web identity
](#cli-configure-role-oidc)
+ [

## Clearing cached credentials
](#cli-configure-role-cache)

## Prerequisites
<a name="cli-role-prereqs"></a>

To run the `iam` commands, you need to install and configure the AWS CLI. This includes setting up a configured profile, as assuming a role is paired with another credential method. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md). 

## Overview of using IAM roles
<a name="cli-role-overview"></a>

You can configure the AWS Command Line Interface (AWS CLI) to use an IAM role by defining a profile for the role in the `~/.aws/config` file. 

The following example shows a role profile named `marketingadmin`. If you run commands with `--profile marketingadmin` (or specify it with the [AWS\$1PROFILE environment variable](cli-configure-envvars.md)), the AWS CLI uses the credentials defined in a separate profile `user1` to assume the role with the Amazon Resource Name (ARN) `arn:aws:iam::123456789012:role/marketingadminrole`. You can run any operations that are allowed by the permissions assigned to that role.

```
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
source_profile = user1
```

You can then specify a `source_profile` that points to a separate named profile that contains user credentials with permission to use the role. In the previous example, the `marketingadmin` profile uses the credentials in the `user1` profile. When you specify that an AWS CLI command is to use the profile `marketingadmin`, the AWS CLI automatically looks up the credentials for the linked `user1` profile and uses them to request temporary credentials for the specified IAM role. The CLI uses the [sts:AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) operation in the background to accomplish this. Those temporary credentials are then used to run the requested AWS CLI command. The specified role must have attached IAM permission policies that allow the requested AWS CLI command to run.

To run a AWS CLI command from within an Amazon Elastic Compute Cloud (Amazon EC2) instance or an Amazon Elastic Container Service (Amazon ECS) container, you can use an IAM role attached to the instance profile or the container. If you specify no profile or set no environment variables, that role is used directly. This enables you to avoid storing long-lived access keys on your instances. You can also use those instance or container roles only to get credentials for another role. To do this, you use `credential_source` (instead of `source_profile`) to specify how to find the credentials. The `credential_source` attribute supports the following values:
+ `Environment` – Retrieves the source credentials from environment variables.
+ `Ec2InstanceMetadata` – Uses the IAM role attached to the Amazon EC2 instance profile.
+ `EcsContainer` – Uses the IAM role attached to the Amazon ECS container.

The following example shows the same `marketingadminrole` role used by referencing an Amazon EC2 instance profile.

```
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
credential_source = Ec2InstanceMetadata
```

When you invoke a role, you have additional options that you can require, such as the use of multi-factor authentication and an External ID (used by third-party companies to access their clients' resources). You can also specify unique role session names that can be more easily audited in AWS CloudTrail logs.

## Configuring and using a role
<a name="cli-role-prepare"></a>

When you run commands using a profile that specifies an IAM role, the AWS CLI uses the source profile's credentials to call AWS Security Token Service (AWS STS) and request temporary credentials for the specified role. The user in the source profile must have permission to call `sts:assume-role` for the role in the specified profile. The role must have a trust relationship that allows the user in the source profile to use the role. The process of retrieving and then using temporary credentials for a role is often referred to as *assuming the role*.

You can create a role in IAM with the permissions that you want users to assume by following the procedure under [Creating a Role to Delegate Permissions to an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html) in the *AWS Identity and Access Management User Guide*. If the role and the source profile's user are in the same account, you can enter your own account ID when configuring the role's trust relationship.

After creating the role, modify the trust relationship to allow the user to assume it. 

The following example shows a trust policy that you could attach to a role. This policy allows the role to be assumed by any user in the account 123456789012, ***if*** the administrator of that account explicitly grants the `sts:AssumeRole` permission to the user.

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

****  

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

------

The trust policy doesn't actually grant permissions. The administrator of the account must delegate the permission to assume the role to individual users by attaching a policy with the appropriate permissions. The following example shows a policy that you can attach to a user that allows the user to assume only the `marketingadminrole` role. For more information about granting a user access to assume a role, see [Granting a User Permission to Switch Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_permissions-to-switch.html) in the *IAM User Guide*.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": "arn:aws:iam::123456789012:role/marketingadminrole"
    }
  ]
}
```

------

The user doesn't need to have additional permissions to run the AWS CLI commands using the role profile. Instead, the permissions to run the command come from those attached to the *role*. You attach permission policies to the role to specify which actions can be performed against which AWS resources. For more information about attaching permissions to a role (which works identically to a user), see [Changing Permissions for an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html) in the *IAM User Guide*.

Now that you have the role profile, role permissions, role trust relationship, and user permissions correctly configured, you can use the role at the command line by invoking the `--profile` option. For example, the following calls the Amazon S3 `ls` command using the permissions attached to the `marketingadmin` role as defined by the example at the beginning of this topic.

```
$ aws s3 ls --profile marketingadmin
```

To use the role for several calls, you can set the `AWS_PROFILE` environment variable for the current session from the command line. While that environment variable is defined, you don't have to specify the `--profile` option on each command. 

**Linux or macOS**

```
$ export AWS_PROFILE=marketingadmin
```

**Windows**

```
C:\> setx AWS_PROFILE marketingadmin
```

For more information about configuring users and roles, see [IAM Identities (users, user groups, and roles)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) and [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id-roles.html) in the *IAM User Guide*.

## Using multi-factor authentication
<a name="cli-configure-role-mfa"></a>

For additional security, you can require that users provide a one-time key generated from a multi-factor authentication (MFA) device, a U2F device, or mobile app when they attempt to make a call using the role profile.

First, you can choose to modify the trust relationship on the IAM role to require MFA. This prevents anyone from using the role without first authenticating by using MFA. For an example, see the `Condition` line in the following example. This policy allows the user named `anika` to assume the role the policy is attached to, but only if they authenticate by using MFA. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:user/anika" },
      "Action": "sts:AssumeRole",
      "Condition": { "Bool": { "aws:multifactorAuthPresent": true } }
    }
  ]
}
```

------

Next, add a line to the role profile that specifies the ARN of the user's MFA device. The following sample `config` file entries show two role profiles that both use the access keys for the user `anika` to request temporary credentials for the role `cli-role`. The user `anika` has permissions to assume the role, granted by the role's trust policy.

```
[profile role-without-mfa]
region = us-west-2
role_arn= arn:aws:iam::128716708097:role/cli-role
source_profile=cli-user

[profile role-with-mfa]
region = us-west-2
role_arn= arn:aws:iam::128716708097:role/cli-role
source_profile = cli-user
mfa_serial = arn:aws:iam::128716708097:mfa/cli-user

[profile cli-user]
region = us-west-2
output = json
```

The `mfa_serial` setting can take an ARN, as shown, or the serial number of a hardware MFA token.

The first profile, `role-without-mfa`, doesn't require MFA. However, because the previous example trust policy attached to the role requires MFA, any attempt to run a command with this profile fails.

```
$ aws iam list-users --profile role-without-mfa

An error occurred (AccessDenied) when calling the AssumeRole operation: Access denied
```

The second profile entry, `role-with-mfa`, identifies an MFA device to use. When the user attempts to run a AWS CLI command with this profile, the AWS CLI prompts the user to enter the one-time password (OTP) that the MFA device provides. If the MFA authentication succeeds, the command performs the requested operation. The OTP is not displayed on the screen.

```
$ aws iam list-users --profile role-with-mfa
Enter MFA code for arn:aws:iam::123456789012:mfa/cli-user:
{
    "Users": [
        {
            ...
```

## Cross-account roles and external ID
<a name="cli-configure-role-xaccount"></a>

You can enable users to use roles that belong to different accounts by configuring the role as a cross-account role. During role creation, set the role type to **Another AWS account**, as described in [Creating a Role to Delegate Permissions to an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html). Optionally, select **Require MFA**. **Require MFA** configures the appropriate condition in the trust relationship, as described in [Using multi-factor authentication](#cli-configure-role-mfa).

If you use an [external ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) to provide additional control over who can use a role across accounts, you must also add the `external_id` parameter to the role profile. You typically use this only when the other account is controlled by someone outside your company or organization.

```
[profile crossaccountrole]
role_arn = arn:aws:iam::234567890123:role/SomeRole
source_profile = default
mfa_serial = arn:aws:iam::123456789012:mfa/saanvi
external_id = 123456
```

## Specifying a role session name for easier auditing
<a name="cli-configure-role-session-name"></a>

When many individuals share a role, auditing becomes more of a challenge. You want to associate each operation invoked with the individual who invoked the action. However, when the individual uses a role, the assumption of the role by the individual is a separate action from the invoking of an operation, and you must manually correlate the two.

You can simplify this by specifying unique role session names when users assume a role. You do this by adding a `role_session_name` parameter to each named profile in the `config` file that specifies a role. The `role_session_name` value is passed to the `AssumeRole` operation and becomes part of the ARN for the role session. It is also included in the AWS CloudTrail logs for all logged operations.

For example, you could create a role-based profile as follows. 

```
[profile namedsessionrole]
role_arn = arn:aws:iam::234567890123:role/SomeRole
source_profile = default
role_session_name = Session_Maria_Garcia
```

This results in the role session having the following ARN.

```
arn:aws:iam::234567890123:assumed-role/SomeRole/Session_Maria_Garcia
```

Also, all AWS CloudTrail logs include the role session name in the information captured for each operation.

## Assume role with web identity
<a name="cli-configure-role-oidc"></a>

You can configure a profile to indicate that the AWS CLI should assume a role using [web identity federation and Open ID Connect (OIDC)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html). When you specify this in a profile, the AWS CLI automatically makes the corresponding AWS STS `AssumeRoleWithWebIdentity` call for you.

**Note**  
When you specify a profile that uses an IAM role, the AWS CLI makes the appropriate calls to retrieve temporary credentials. These credentials are stored in `~/.aws/cli/cache`. Subsequent AWS CLI commands that specify the same profile use the cached temporary credentials until they expire. At that point, the AWS CLI automatically refreshes the credentials.

To retrieve and use temporary credentials using web identity federation, you can specify the following configuration values in a shared profile.

[role\$1arn](#cli-configure-role)  
Specifies the ARN of the role to assume.

web\$1identity\$1token\$1file  
Specifies the path to a file which contains an OAuth 2.0 access token or OpenID Connect ID token that is provided by the identity provider. The AWS CLI loads this file and passes its content as the `WebIdentityToken` argument of the `AssumeRoleWithWebIdentity` operation.

[role\$1session\$1name](#cli-configure-role-session-name)  
Specifies an optional name applied to this assume-role session.

The following is an example of the minimal amount of configuration needed to configure an assume role with web identity profile.

```
# In ~/.aws/config

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

You can also provide this configuration by using [environment variables](cli-configure-envvars.md).

AWS\$1ROLE\$1ARN  
The ARN of the role to assume.

AWS\$1WEB\$1IDENTITY\$1TOKEN\$1FILE  
The path to the web identity token file.

AWS\$1ROLE\$1SESSION\$1NAME  
The name applied to this assume-role session.

**Note**  
These environment variables currently apply only to the assume role with web identity provider. They don't apply to the general assume role provider configuration.

## Clearing cached credentials
<a name="cli-configure-role-cache"></a>

When you use a role, the AWS CLI caches the temporary credentials locally until they expire. The next time you try to use them, the AWS CLI attempts to renew them on your behalf. 

If your role's temporary credentials are [revoked](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_revoke-sessions.html), they are not renewed automatically, and attempts to use them fail. However, you can delete the cache to force the AWS CLI to retrieve new credentials.

**Linux or macOS**

```
$ rm -r ~/.aws/cli/cache
```

**Windows**

```
C:\> del /s /q %UserProfile%\.aws\cli\cache
```

# Authenticating using IAM user credentials for the AWS CLI
<a name="cli-authentication-user"></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).

This section explains how to configure basic settings with an IAM user. These include your security credentials using the `config` and `credentials` files. To instead see configuration instructions for AWS IAM Identity Center, see [Configuring IAM Identity Center authentication with the AWS CLI](cli-configure-sso.md).

**Contents**
+ [

## Step 1: Create your IAM user
](#cli-authentication-user-create)
+ [

## Step 2: Get your access keys
](#cli-authentication-user-get)
+ [

## Step 3: Configure the AWS CLI
](#cli-authentication-user-configure.title)
  + [

### Using `aws configure`
](#cli-authentication-user-configure-wizard)
  + [

### Importing access keys via .CSV file
](#cli-authentication-user-configure-csv)
  + [

### Directly editing the `config` and `credentials` files
](#cli-authentication-user-configure-csv.titlecli-authentication-user-configure-file)
+ [

## (Optional) Using multi-factor authentication with your IAM user credentials
](#cli-authentication-user-configure-csv.titlecli-authentication-user-mfa)

## Step 1: Create your IAM user
<a name="cli-authentication-user-create"></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*. 
+ For **Permission options**, choose **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.

## Step 2: Get your access keys
<a name="cli-authentication-user-get"></a>

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 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 **Command Line Interface (CLI)**.

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.

1. Select Done.

## Step 3: Configure the AWS CLI
<a name="cli-authentication-user-configure.title"></a>

For general use, the AWS CLI needs the following pieces of information:
+ Access key ID
+ Secret access key
+ AWS Region
+ Output format

The AWS CLI stores this information in a *profile* (a collection of settings) named `default` in the `credentials` file. By default, the information in this profile is used when you run an AWS CLI command that doesn't explicitly specify a profile to use. For more information on the `credentials` file, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md).

To configure the AWS CLI, use one of the following procedures:

**Topics**
+ [

### Using `aws configure`
](#cli-authentication-user-configure-wizard)
+ [

### Importing access keys via .CSV file
](#cli-authentication-user-configure-csv)
+ [

### Directly editing the `config` and `credentials` files
](#cli-authentication-user-configure-csv.titlecli-authentication-user-configure-file)

### Using `aws configure`
<a name="cli-authentication-user-configure-wizard"></a>

For general use, the `aws configure` command is the fastest way to set up your AWS CLI installation. This configure wizard prompts you for each piece of information you need to get started. Unless otherwise specified by using the `--profile` option, the AWS CLI stores this information in the `default` profile.

The following example configures a `default` profile using sample values. Replace them with your own values as described in the following sections.

```
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
```

The following example configures a profile named `userprod` using sample values. Replace them with your own values as described in the following sections.

```
$ aws configure --profile userprod
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
```

### Importing access keys via .CSV file
<a name="cli-authentication-user-configure-csv"></a>

Instead of using `aws configure` to enter in access keys, you can import the plain text `.csv` file you downloaded after you created your access keys. 

The `.csv` file must contain the following headers.
+ User Name - This column must be added to your `.csv`. This is used to create the profile name used in the the `config` and `credentials` files when you import.
+ Access key ID
+ Secret access key

**Note**  
During initial access keys creation, once you close the **Download .csv file** dialog box, you cannot access your secret access key after you close the dialog box. If you need a `.csv` file, you'll need to create one yourself with the required headers and your stored access keys information. If you do not have access to your access keys information, you need to create a new access keys.

To import the `.csv` file, use the `aws configure import` command with the `--csv` option as follows:

```
$ aws configure import --csv file://credentials.csv
```

For more information, see `aws\$1configure\$1import`.

### Directly editing the `config` and `credentials` files
<a name="cli-authentication-user-configure-csv.titlecli-authentication-user-configure-file"></a>

To directly edit the `config` and `credentials` files, perform the following.

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 [Configuration and credential file settings in the AWS CLI](cli-configure-files.md). 

1. Add the following text to the shared `credentials` file. Replace the sample values in the `.csv` file that you downloaded earlier and save the file. 

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

## (Optional) Using multi-factor authentication with your IAM user credentials
<a name="cli-authentication-user-configure-csv.titlecli-authentication-user-mfa"></a>

For additional security, you can use a one-time key generated from a multi-factor authentication (MFA) device, a U2F device, or mobile app when you attempt to make a call.

With your MFA enabled IAM user, run the [https://docs.aws.amazon.com/cli/latest/reference/configure/mfa-login.html](https://docs.aws.amazon.com/cli/latest/reference/configure/mfa-login.html) command to configure a new profile to use with multi-factor authentication (MFA) for the specified profile. If no profile is specified, the MFA is based on the `default` profile. If no default profile is configured, the `mfa-login` command prompts you for you AWS credentials before asking for your MFA information. The following command example uses your default configuration and creates an MFA profile.

```
$ aws configure mfa-login
MFA serial number or ARN: arn:aws:iam::123456789012:mfa/MFADeviceName
MFA token code: 123456
Profile to update [session-MFADeviceName]:
Temporary credentials written to profile 'session-MFADeviceName'
Credentials will expire at 2023-05-19 18:06:10 UTC
To use these credentials, specify --profile session-MFADeviceName when running AWS CLI commands
```

To update an existing profile, use the `--update-profile` parameter.

```
$ aws configure mfa-login --profile myprofile --update-profile mfaprofile
MFA token code: 123456
Temporary credentials written to profile 'mfaprofile'
Credentials will expire at 2023-05-19 18:06:10 UTC
To use these credentials, specify --profile mfaprofile when running AWS CLI commands
```

This command currently supports only hardware or software based one-time password (OTP) authenticators. Passkeys and U2F devices are not currently supported with this command.

To use your MFA profile, use the `--profile` option with your commands.

```
$ aws s3 ls --profile mfaprofile
```

For more information on using MFA with IAM, including how to assign MFA to an IAM user, see [AWS Multi-factor authentication in IAM ](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html) in the *AWS Identity and Access Management User Guide*.

# Using Amazon EC2 instance metadata as credentials in the AWS CLI
<a name="cli-configure-metadata"></a>

When you run the AWS CLI from within an Amazon Elastic Compute Cloud (Amazon EC2) instance, you can simplify providing credentials to your commands. Each Amazon EC2 instance contains metadata that the AWS CLI can directly query for temporary credentials. When an IAM role is attached to the instance, the AWS CLI automatically and securely retrieves the credentials from the instance metadata. 

To disable this service, use the [AWS\$1EC2\$1METADATA\$1DISABLED](cli-configure-envvars.md#envvars-list-AWS_EC2_METADATA_DISABLED) environment variable.

**Topics**
+ [

## Prerequisites
](#cli-configure-metadata-prereqs)
+ [

## Configuring a profile for Amazon EC2 metadata
](#cli-configure-metadata-configure)

## Prerequisites
<a name="cli-configure-metadata-prereqs"></a>

To use Amazon EC2 credentials with the AWS CLI, you need to complete the following:
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ You understand configuration files and named profiles. For more information, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md). 
+ You've created an AWS Identity and Access Management (IAM) role that has access to the resources needed, and attached that role to the Amazon EC2 instance when you launch it. For more information, see [IAM policies for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html) in the *Amazon EC2 User Guide* and [Granting Applications That Run on Amazon EC2 Instances Access to AWS Resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/role-usecase-ec2app.html) in the *IAM User Guide*.

## Configuring a profile for Amazon EC2 metadata
<a name="cli-configure-metadata-configure"></a>

To specify that you want to use the credentials available in the hosting Amazon EC2 instance profile, use the following syntax in the named profile in your configuration file. See the following steps for more instructions. 

```
[profile profilename]
role_arn = arn:aws:iam::123456789012:role/rolename
credential_source = Ec2InstanceMetadata
region = region
```

1. Create a profile in your configuration file.

   ```
   [profile profilename]
   ```

1. Add your IAM arn role that has access to the resources needed.

   ```
   role_arn = arn:aws:iam::123456789012:role/rolename
   ```

1. Specify `Ec2InstanceMetadata` as your credential source.

   ```
   credential_source = Ec2InstanceMetadata
   ```

1. Set your Region.

   ```
   region = region
   ```

**Example**

The following example assumes the *`marketingadminrole`* role and uses the `us-west-2` Region in an Amazon EC2 instance profile named `marketingadmin`.

```
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
credential_source = Ec2InstanceMetadata
region = us-west-2
```

# Sourcing credentials with an external process in the AWS CLI
<a name="cli-configure-sourcing-external"></a>

**Warning**  
This topic discusses sourcing credentials from an external process. This could be a security risk if the command to generate the credentials becomes accessible by non-approved processes or users. We recommend that you use the supported, secure alternatives provided by the AWS CLI and AWS to reduce the risk of compromising your credentials. Ensure that you secure the `config` file and any supporting files and tools to prevent disclosure.  
Ensure that your custom credential tool does not write any secret information to `StdErr` because the SDKs and AWS CLI can capture and log such information, potentially exposing it to unauthorized users.

If you have a method to generate or look up credentials that isn't directly supported by the AWS CLI, you can configure the AWS CLI to use it by configuring the `credential_process` setting in the `config` file. 

For example, you might include an entry similar to the following in the `config` file.

```
[profile developer]
credential_process = /opt/bin/awscreds-custom --username helen
```

**Syntax**  
To create this string in a way that is compatible with any operating system, follow these rules:
+ If the path or file name contains a space, surround the complete path and file name with double-quotation marks (" "). The path and file name can consist of only the characters: A-Z a-z 0-9 - \$1 . space
+ If a parameter name or a parameter value contains a space, surround that element with double-quotation marks (" "). Surround only the name or value, not the pair.
+ Do not include any environment variables in the strings. For example, you can't include `$HOME` or `%USERPROFILE%`.
+ Do not specify the home folder as `~`. You must specify the full path.

**Example for Windows**

```
credential_process = "C:\Path\To\credentials.cmd" parameterWithoutSpaces "parameter with spaces"
```

**Example for Linux or macOS**

```
credential_process = "/Users/Dave/path/to/credentials.sh" parameterWithoutSpaces "parameter with spaces"
```

**Expected output from the Credentials program**

The AWS CLI runs the command as specified in the profile and then reads data from `STDOUT`. The command you specify must generate JSON output on `STDOUT` that matches the following syntax.

```
{
  "Version": 1,
  "AccessKeyId": "an AWS access key",
  "SecretAccessKey": "your AWS secret access key",
  "SessionToken": "the AWS session token for temporary credentials", 
  "Expiration": "ISO8601 timestamp when the credentials expire"
}
```

**Note**  
As of this writing, the `Version` key must be set to `1`. This might increment over time as the structure evolves.

The `Expiration` key is an [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) formatted timestamp. If the `Expiration` key is not present in the tool's output, the CLI assumes that the credentials are long-term credentials that do not refresh. Otherwise the credentials are considered temporary credentials and are refreshed automatically by rerunning the `credential_process` command before they expire.

**Note**  
The AWS CLI does ***not*** cache external process credentials the way it does assume-role credentials. If caching is required, you must implement it in the external process.

The external process can return a non-zero return code to indicate that an error occurred while retrieving the credentials.