

# IAM Identities
Identities

An IAM identity can be associated with one or more policies, which determine what actions an identity is authorized to perform, on which AWS resources, and under what conditions. IAM identities include IAM users, IAM groups, and IAM roles. An IAM entity is a type of identity that represents a human user or programmatic workload that can be authenticated and then authorized to perform actions in AWS accounts. IAM entities include IAM users and IAM roles. For definitions for commonly used terms, see [Terms](introduction_identity-management.md#intro-structure-terms).

You can federate existing identities from an external identity provider. These identities will assume IAM roles to access AWS resources. For more information, see [Identity providers and federation into AWS](id_roles_providers.md).

You can also use AWS IAM Identity Center to create and manage identities and access to AWS resources. IAM Identity Center permission sets automatically create the IAM roles needed to provide access to resources. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)

The AWS account root user is an AWS account principal that is created when your AWS account is established. The root user has access to all AWS services and resources in the account. For more information, see [IAM root user](#id_root). 

**Note**  
Follow the [Security best practices in IAM](https://docs.aws.amazon.com//IAM/latest/UserGuide/best-practices-use-cases.html) when working with IAM identities. 
Follow the [root user best practices for your AWS account](root-user-best-practices.md) when working with the root user.
If you're having trouble signing in, see [Sign in to the AWS Management Console](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html). 

## IAM root user


When you first create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account *root user*. For more information, see [AWS account root user.](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html)

## IAM users


An *IAM user *is an identity within your AWS account that has specific permissions for a single person or application. For more information, see [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html). 

## IAM user groups


An *IAM user group* is an identity that specifies a collection of IAM users. For more information, see [User groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html).

## IAM roles


An *IAM role* is an identity within your AWS account that has specific permissions. It's similar to an IAM user, but isn't associated with a specific person. For more information, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html).

# AWS account root user


When you first create an Amazon Web Services (AWS) account, you begin with a single sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account *root user*. The email address and password that you used to create your AWS account are the credentials you use to sign in as your root user.
+ Use the root user only to perform the tasks that require root-level permissions. For the complete list of tasks that require you to sign in as the root user, see [Tasks that require root user credentials](#root-user-tasks). 
+ Follow the [root user best practices for your AWS account](root-user-best-practices.md).
+ If you're having trouble signing in, see [Sign in to the AWS Management Console](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html).

**Important**  
We strongly recommend that you don't use the root user for your everyday tasks and that you follow the [root user best practices for your AWS account](root-user-best-practices.md). Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see [Tasks that require root user credentials](#root-user-tasks). 

While MFA is enforced for root users by default, it requires customer action to add MFA during the initial account creation or as prompted during sign-in. For more information about using MFA to protect the root user, see [Multi-factor authentication for AWS account root user](enable-mfa-for-root.md).

## Centrally manage root access for member accounts


To help you manage credentials at scale, you can centrally secure access to root user credentials for member accounts in AWS Organizations. When you enable AWS Organizations, you combine all your AWS accounts into an organization for central management. Centralizing root access lets you remove root user credentials and perform the following privileged tasks on member accounts.

**Remove member account root user credentials**  
After you [centralize root access for member accounts](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html), you can choose to delete root user credentials from member accounts in your Organizations. You can remove the root user password, access keys, signing certificates, and deactivate multi-factor authentication (MFA). New accounts you create in Organizations have no root user credentials by default. Member accounts can't sign in to their root user or perform password recovery for their root user unless account recovery is enabled.

**Perform privileged tasks that require root user credentials**  
Some tasks can only be performed when you sign in as the root user of an account. Some of these [Tasks that require root user credentials](#root-user-tasks) can be performed by the management account or delegated administrator for IAM. To learn more about taking privileged actions on member accounts, see [Perform a privileged task](id_root-user-privileged-task.md).

**Enable account recovery of the root user**  
If you need to recover root user credentials for a member account, the Organizations management account or delegated administrator can perform the **Allow password recovery** privileged task. The person with access to the root user email inbox for the member account can [reset the root user password](https://docs.aws.amazon.com/IAM/latest/UserGuide/reset-root-password.html) to recover root user credentials. We recommend deleting root user credentials once you complete the task that requires access to the root user.

# Centralize root access for member accounts
Centralize root access

Root user credentials are the initial credentials assigned to each AWS account that has complete access to all AWS services and resources in the account. When you enable AWS Organizations, you combine all your AWS accounts into an organization for central management. Each member account has its own root user with default permissions to perform any action in the member account. We recommend you centrally secure the root user credentials of AWS accounts managed using AWS Organizations to prevent root user credential recovery and access at scale.

After you centralize root access, you can choose to delete root user credentials from member accounts in your organization. You can remove the root user password, access keys, signing certificates, and deactivate multi-factor authentication (MFA). New accounts you create in AWS Organizations have no root user credentials by default. Member accounts can't sign in to their root user or perform password recovery for their root user.

**Note**  
While some [Tasks that require root user credentials](id_root-user.md#root-user-tasks) can be performed by the management account or delegated administrator for IAM, some tasks can only be performed when you sign in as the root user of an account.  
If you need to recover root user credentials for a member account to perform one of these tasks, follow the steps in [Perform a privileged task](id_root-user-privileged-task.md) and select **Allow password recovery**. The person with access to the root user email inbox for the member account can then follow the steps to [ reset the root user password](https://docs.aws.amazon.com/IAM/latest/UserGuide/reset-root-password.html) and sign in to the member account root user.  
 We recommend deleting root user credentials once you complete the task that requires access to the root user.

## Prerequisites


Before you centralize root access, you must have an account configured with the following settings:
+ You must have the following IAM permissions:
  + `iam:GetAccessKeyLastUsed`
  + `iam:GetAccountSummary`
  + `iam:GetLoginProfile`
  + `iam:GetUser`
  + `iam:ListAccessKeys`
  + `iam:ListMFADevices`
  + `iam:ListSigningCertificates`
  + `sts:AssumeRoot`
**Note**  
To audit the root user credential status of a member account, you can use the [IAMAuditRootUserCredentials](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMAuditRootUserCredentials) AWS managed policy to scope down permissions when you perform a privileged task on an AWS Organizations member account, or use any policy with access to `iam:GetAccountSummary`.  
To generate the root user credential information report, other policies only need the `iam:GetAccountSummary` action to produce the same output. You can also list or get individual root user credential information, including:  
Whether a root user password is present
Whether a root user access key is present and when it was last used
Whether the root user has associated signing certificates
Root user associated MFA devices
List of the consolidated root user credential status
+ You must manage your AWS accounts in [AWS Organizations](https://docs.aws.amazon.com//organizations/latest/userguide/orgs_introduction.html).
+ You must have the following permissions to enable this feature in your organization:
  + `iam:EnableOrganizationsRootCredentialsManagement`
  + `iam:EnableOrganizationsRootSessions`
  + `iam:ListOrganizationsFeatures`
  + `organizations:EnableAwsServiceAccess`
  + `organizations:ListAccountsForParent`
  + `organizations:RegisterDelegatedAdministrator` 
+ To ensure optimal console functionality, we recommend enabling the following additional permissions:
  + `organizations:DescribeAccount`
  + `organizations:DescribeOrganization`
  + `organizations:ListAWSServiceAccessForOrganization`
  + `organizations:ListDelegatedAdministrators`
  + `organizations:ListOrganizationalUnitsForParent`
  + `organizations:ListParents`
  + `organizations:ListTagsForResource`

## Enabling centralized root access (console)


**To enable this feature for member accounts in the AWS Management Console**

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 console, choose **Root access management**, and then select **Enable**.
**Note**  
If you see **Root access management is disabled**, enable trusted access for AWS Identity and Access Management in AWS Organizations. For details, see [AWS IAM and AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/services-that-can-integrate-iam.html) in the *AWS Organizations User Guide*.

1. In the Capabilities to enable section, choose which features to enable.
   + Select **Root credentials management** to allow the management account and the delegated administrator for IAM to delete root user credentials for member accounts. You must enable Privileged root actions in member accounts to allow member accounts to recover their root user credentials after they have been deleted.
   + Select **Privileged root actions in member accounts** to allow the management account and the delegated administrator for IAM to perform certain tasks that require root user credentials.

1. (Optional) Enter the account ID of the **Delegated administrator** that is authorized to manage root user access and take privileged actions on member accounts. We recommend an account that is intended for security or management purposes.

1. Choose **Enable**.

## Enabling centralized root access (AWS CLI)


**To enable centralized root access from the AWS Command Line Interface (AWS CLI)**

1. If you haven't already enabled trusted access for AWS Identity and Access Management in AWS Organizations, use the following command: [aws organizations enable-aws-service-access](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/enable-aws-service-access.html).

1. Use the following command to allow the management account and the delegated administrator to delete root user credentials for member accounts: [aws iam enable-organizations-root-credentials-management](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-organizations-root-credentials-management.html).

1. Use the following command to allow the management account and the delegated administrator to perform certain tasks that require root user credentials: [aws iam enable-organizations-root-sessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-organizations-root-sessions.html).

1. (Optional) Use the following command to register a delegated administrator: [aws organizations register-delegated-administrator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/register-delegated-administrator.html).

   The following example assigns account 111111111111 as the delegated administrator for the IAM service.

   ```
   aws organizations register-delegated-administrator 
   --service-principal iam.amazonaws.com
   --account-id 111111111111
   ```

## Enabling centralized root access (AWS API)


**To enable centralized root access from the AWS API**

1. If you haven't already enabled trusted access for AWS Identity and Access Management in AWS Organizations, use the following command: [EnableAWSServiceAccess](https://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html).

1. Use the following command to allow the management account and the delegated administrator to delete root user credentials for member accounts: [EnableOrganizationsRootCredentialsManagement](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableOrganizationsRootCredentialsManagement.html).

1. Use the following command to allow the management account and the delegated administrator to perform certain tasks that require root user credentials: [EnableOrganizationsRootSessions](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableOrganizationsRootSessions.html).

1. (Optional) Use the following command to register a delegated administrator: [RegisterDelegatedAdministrator](https://docs.aws.amazon.com/organizations/latest/APIReference/API_RegisterDelegatedAdministrator.html).

## Next steps


Once you've centrally secured privileged credentials for the member accounts in your organization, see [Perform a privileged task](id_root-user-privileged-task.md) to take privileged actions on a member account.

# Perform a privileged task on an AWS Organizations member account
Perform a privileged task

The AWS Organizations management account or a delegated administrator account for IAM can perform some privileged tasks on member accounts that would otherwise require root user credentials. With centralized root access, these tasks are performed through short-term privileged sessions. These sessions provide temporary credentials scoped to specific privileged actions, without requiring root user sign-in on the member account.

Once you launch a privileged session, you can delete a misconfigured Amazon S3 bucket policy, delete a misconfigured Amazon SQS queue policy, delete the root user credentials for a member account, and reenable root user credentials for a member account.

**Note**  
To use centralized root access, you must sign in via a management account or a delegated administrator account as an IAM user or role with the `sts:AssumeRoot` permission explicitly granted. You cannot use root user credentials to call `sts:AssumeRoot`.

## Prerequisites


Before you can launch a privileged session, you must have the following settings:
+ You have enabled centralized root access in your organization. For steps to enable this feature, see [Centralize root access for member accounts](id_root-enable-root-access.md).
+ Your management account or delegated administrator account has the following permissions: `sts:AssumeRoot`

## Taking a privileged action on a member account (console)


**To launch a session for privileged action in a member account in the AWS Management Console**

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 console, choose **Root access management**.

1. Select a name from the member account list, and choose **Take privileged action**.

1. Choose the privileged action you want to take in the member account.
   + Select **Delete Amazon S3 bucket policy** to remove a misconfigured bucket policy that denies all principals from accessing the Amazon S3 bucket.

     1. Choose **Browse S3** to select a name from the buckets owned by the member account, and select **Choose**.

     1. Choose **Delete bucket policy**.

     1. Use the Amazon S3 console to correct the bucket policy after deleting the misconfigured policy. For more information, see [Adding a bucket policy by using the Amazon S3 console](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html) in the *Amazon S3 User Guide*.
   + Select **Delete Amazon SQS policy** to delete an Amazon Simple Queue Service resource-based policy that denies all principals from accessing an Amazon SQS queue.

     1. Enter the queue name in **SQS queue name**, and select **Delete SQS policy**.

     1. Use the Amazon SQS console to correct the queue policy after deleting the misconfigured policy. For more information, see [Configuring an access policy in Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-add-permissions.html) in the *Amazon SQS Developer Guide*.
   + Select **Delete root credentials** to remove root access from a member account. Deleting root user credentials removes the root user password, access keys, signing certificates, and deactivates multi-factor authentication (MFA) for the member account.

     1. Choose **Delete root credentials**.
   + Select **Allow password recovery** to recover root user credentials for a member account.

     This option is only available when the member account has no root user credentials.

     1. Choose **Allow password recovery**.

     1. After taking this privileged action, the person with access to the root user email inbox for the member account can [ reset the root user password](https://docs.aws.amazon.com/IAM/latest/UserGuide/reset-root-password.html) and sign in to the member account root user.

## Taking a privileged action on a member account (AWS CLI)


**To launch a session for privileged action in a member account from the AWS Command Line Interface**

1. Use the following command to assume a root user session: [aws sts assume-root](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-root.html).
**Note**  
The global endpoint is not supported for `sts:AssumeRoot`. You must send this request to a Regional AWS STS endpoint. For more information, see [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).

   When you launch a privileged root user session for a member account, you must define `task-policy-arn` to scope the session to the privileged action to be performed during the session. You can use one of following AWS managed policies to scope privileged session actions.
   + [IAMAuditRootUserCredentials](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMAuditRootUserCredentials)
   + [IAMCreateRootUserPassword](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMCreateRootUserPassword)
   + [IAMDeleteRootUserCredentials](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMDeleteRootUserCredentials)
   + [S3UnlockBucketPolicy](security-iam-awsmanpol.md#security-iam-awsmanpol-S3UnlockBucketPolicy)
   + [SQSUnlockQueuePolicy](security-iam-awsmanpol.md#security-iam-awsmanpol-SQSUnlockQueuePolicy)

   To limit the actions a management account or delegated administrator can perform during a privileged root user session, you can use the AWS STS condition key [sts:TaskPolicyArn](reference_policies_iam-condition-keys.md#ck_taskpolicyarn).

    In the following example, the delegated administrator assumes root to delete the root user credentials for the member account ID *111122223333*. 

   ```
   aws sts assume-root \
     --target-principal 111122223333 \
     --task-policy-arn arn=arn:aws:iam::aws:policy/root-task/IAMDeleteRootUserCredentials \
     --duration-seconds 900
   ```

1. Use the `SessionToken`, `AccessKeyId`, and `SecretAccessKey` from the response to perform privileged actions in the member account. You can omit the user name and password in the request to default to the member account.
   + **Check the status of root user credentials**. Use the following commands to check the status of root user credentials for a member account.
     + [get-user](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user.html)
     + [get-login-profile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-login-profile.html)
     + [list-access-keys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-access-keys.html)
     + [list-signing-certificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-signing-certificates.html)
     + [list-mfa-devices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-mfa-devices.html)
     + [get-access-key-last-used](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-access-key-last-used.html)
   + **Delete root user credentials**. Use the following commands to delete root access. You can remove the root user password, access keys, signing certificates, and deactivate multi-factor authentication (MFA) to remove all access to and recovery of the root user.
     + [delete-login-profile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-login-profile.html)
     + [delete-access-key](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-access-key.html)
     + [delete-signing-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-signing-certificate.html)
     + [deactivate-mfa-device](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html)
   + **Delete Amazon S3 bucket policy**. Use the following commands to read, edit, and delete a misconfigured bucket policy that denies all principals from accessing the Amazon S3 bucket.
     + [list-buckets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-buckets.html)
     + [get-bucket-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-policy.html)
     + [put-bucket-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-policy.html)
     + [delete-bucket-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-policy.html)
   + **Delete Amazon SQS policy**. Use the following commands to view and delete an Amazon Simple Queue Service resource-based policy that denies all principals from accessing an Amazon SQS queue.
     + [list-queues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/list-queues.html)
     + [get-queue-url](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/get-queue-url.html)
     + [get-queue-attributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/get-queue-attributes.html)
     + [set-queue-attributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/set-queue-attributes.html)
   + **Allow password recovery**. Use the following commands to view the user name and recover root user credentials for a member account.
     + [get-login-profile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-login-profile.html)
     + [create-login-profile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-login-profile.html)

## Taking a privileged action on a member account (AWS API)


**To launch a session for privileged action in a member account from the AWS API**

1. Use the following command to assume a root user session: [AssumeRoot](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoot.html).
**Note**  
The global endpoint is not supported for AssumeRoot. You must send this request to a Regional AWS STS endpoint. For more information, see [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).

   When you launch a privileged root user session for a member account, you must define `TaskPolicyArn` to scope the session to the privileged action to be performed during the session. You can use one of following AWS managed policies to scope privileged session actions.
   + [IAMAuditRootUserCredentials](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMAuditRootUserCredentials)
   + [IAMCreateRootUserPassword](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMCreateRootUserPassword)
   + [IAMDeleteRootUserCredentials](security-iam-awsmanpol.md#security-iam-awsmanpol-IAMDeleteRootUserCredentials)
   + [S3UnlockBucketPolicy](security-iam-awsmanpol.md#security-iam-awsmanpol-S3UnlockBucketPolicy)
   + [SQSUnlockQueuePolicy](security-iam-awsmanpol.md#security-iam-awsmanpol-SQSUnlockQueuePolicy)

   To limit the actions a management account or delegated administrator can perform during a privileged root user session, you can use the AWS STS condition key [sts:TaskPolicyArn](reference_policies_iam-condition-keys.md#ck_taskpolicyarn).

   In the following example, the delegated administrator assumes root to read, edit and delete a misconfigured resource-based policy for an Amazon S3 bucket for the member account ID *111122223333*.

   ```
   https://sts.us-east-2.amazonaws.com/
     ?Version=2011-06-15
     &Action=AssumeRoot
     &TargetPrincipal=111122223333
     &PolicyArns.arn=arn:aws:iam::aws:policy/root-task/S3UnlockBucketPolicy 
     &DurationSeconds 900
   ```

1. Use the `SessionToken`, `AccessKeyId`, and `SecretAccessKey` from the response to perform privileged actions in the member account. You can omit the user name and password in the request to default to the member account.
   + **Check the status of root user credentials**. Use the following commands to check the status of root user credentials for a member account.
     + [GetUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html)
     + [GetLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html)
     + [ListAccessKeys](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html)
     + [ListSigningCertificates](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSigningCertificates.html)
     + [ListMFADevices](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADevices.html)
     + [GetAccessKeyLastUsed](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html)
   + **Delete root user credentials**. Use the following commands to delete root access. You can remove the root user password, access keys, signing certificates, and deactivate multi-factor authentication (MFA) to remove all access to and recovery of the root user.
     + [DeleteLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteLoginProfile.html)
     + [DeleteAccessKey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html)
     + [DeleteSigningCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSigningCertificate.html)
     + [DeactivateMfaDevice](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html)
   + **Delete Amazon S3 bucket policy**. Use the following commands to read, edit, and delete a misconfigured bucket policy that denies all principals from accessing the Amazon S3 bucket.
     + [ListBuckets](https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBuckets.html)
     + [GetBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicy.html)
     + [PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketPolicy.html)
     + [DeleteBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketPolicy.html)
   + **Delete Amazon SQS policy**. Use the following commands to view and delete an Amazon Simple Queue Service resource-based policy that denies all principals from accessing an Amazon SQS queue.
     + [ListQueues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ListQueues.html)
     + [GetQueueUrl](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueUrl.html)
     + [GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html)
     + [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)
   + **Allow password recovery**. Use the following commands to view the user name and recover root user credentials for a member account.
     + [GetLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html)
     + [CreateLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html)

# Multi-factor authentication for AWS account root user
MFA for the root user

**Important**  
AWS recommends that you use a passkey or security key for MFA to AWS, wherever possible as they are more resistant to attacks such as phishing. For more information, see [Passkeys and security keys](#passkeys-security-keys-for-root).

Multi-factor authentication (MFA) is a simple and effective mechanism to enhance your security. The first factor — your password — is a secret that you memorize, also known as a knowledge factor. Other factors can be possession factors (something you have, such as a security key) or inherence factors (something you are, such as a biometric scan). For increased security, we strongly recommend that you configure multi-factor authentication (MFA) to help protect your AWS resources.

**Note**  
All AWS account types (standalone, management, and member accounts) require MFA to be configured for their root user. Users must register MFA within 35 days of their first sign-in attempt to access the AWS Management Console if MFA is not already enabled.

You can enable MFA for the AWS account root user and IAM users. When you enable MFA for the root user, it only affects the root user credentials. For more information about how to enable MFA for your IAM users, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md).

**Note**  
AWS accounts managed using AWS Organizations may have the option to [centrally manage root access](id_root-user.md#id_root-user-access-management) for member accounts to prevent credential recovery and access at scale. If this option is enabled, you can delete root user credentials from member accounts, including passwords and MFA, effectively preventing sign-in as the root user, password recovery, or setting up MFA. Alternatively, if you prefer to maintain password-based sign-in methods, secure your account by registering MFA to enhance account protection.

Before you enable MFA for your root user, review and [update your account settings and contact information](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-root-user.html) to make sure that you have access to the email and phone number. If your MFA device is lost, stolen, or not working, you can still sign in as the root user by verifying your identity using that email and phone number. To learn about signing in using alternative factors of authentication, see [Recover an MFA protected identity in IAM](id_credentials_mfa_lost-or-broken.md). To disable this feature, contact [AWS Support](https://console.aws.amazon.com/support/home#/). 

AWS supports the following MFA types for your root user:
+ [Passkeys and security keys](#passkeys-security-keys-for-root)
+ [Virtual authenticator applications](#virtual-auth-apps-for-root)
+ [Hardware TOTP tokens](#hardware-totp-token-for-root)

## Passkeys and security keys


AWS Identity and Access Management supports passkeys and security keys for MFA. Based on FIDO standards, passkeys use public key cryptography to provide strong, phishing-resistant authentication that is more secure than passwords. AWS supports two types of passkeys: device-bound passkeys (security keys) and synced passkeys.
+ **Security keys**: These are physical devices, like a YubiKey, used as a second factor for authentication. A single security key can support multiple root user accounts and IAM users. 
+ **Synced passkeys**: These use credential managers from providers such as Google, Apple, Microsoft accounts, and third-party services like 1Password, Dashlane, and Bitwarden as a second factor.

You can use built-in biometric authenticators, like Touch ID on Apple MacBooks, to unlock your credential manager and sign in to AWS. Passkeys are created with your chosen provider using your fingerprint, face, or device PIN. You can also use a cross-device authentication (CDA) passkey from one device, like a mobile device or hardware security key, to sign in on another device like a laptop. For more information, see [cross-device authentication](https://passkeys.dev/docs/reference/terms/#cross-device-authentication-cda) (CDA).

You can sync passkeys across your devices to facilitate sign-ins with AWS, enhancing usability and recoverability. For more information about enabling passkeys and security keys, see [Enable a passkey or security key for the root user (console)](enable-fido-mfa-for-root.md).

The FIDO Alliance maintains a list of all [FIDO Certified products](https://fidoalliance.org/certification/fido-certified-products/) that are compatible with FIDO specifications.

## Virtual authenticator applications


A virtual authenticator application runs on a phone or other device and emulates a physical device. Virtual authenticator apps implement the [time-based one-time password (TOTP) algorithm](https://datatracker.ietf.org/doc/html/rfc6238) and support multiple tokens on a single device. The user must type a valid code from the device when prompted during sign-in. Each token assigned to a user must be unique. A user can't type a code from another user's token to authenticate.

We do recommend that you use a virtual MFA device while waiting for hardware purchase approval or while you wait for your hardware to arrive. For a list of a few supported apps that you can use as virtual MFA devices, see [Multi-Factor Authentication (MFA)](https://aws.amazon.com/iam/features/mfa/?audit=2019q1). For instructions on setting up a virtual MFA device with AWS, see [Enable a virtual MFA device for the root user (console)](enable-virt-mfa-for-root.md).

## Hardware TOTP tokens


A hardware device generates a six-digit numeric code based on the [time-based one-time password (TOTP) algorithm](https://datatracker.ietf.org/doc/html/rfc6238). The user must type a valid code from the device on a second webpage during sign-in. Each MFA device assigned to a user must be unique. A user cannot type a code from another user's device to be authenticated. For information on supported hardware MFA devices, see [Multi-Factor Authentication (MFA)](https://aws.amazon.com/iam/features/mfa/?audit=2019q1). For instructions on setting up a hardware TOTP token with AWS, see [Enable a hardware TOTP token for the root user (console)](enable-hw-mfa-for-root.md).

If you want to use a physical MFA device, we recommend that you use FIDO security keys as an alternative to hardware TOTP devices. FIDO security keys offer the benefits of no battery requirements, phishing resistance, and they support multiple root and IAM users on a single device for enhanced security.

**Topics**
+ [

## Passkeys and security keys
](#passkeys-security-keys-for-root)
+ [

## Virtual authenticator applications
](#virtual-auth-apps-for-root)
+ [

## Hardware TOTP tokens
](#hardware-totp-token-for-root)
+ [

# Enable a passkey or security key for the root user (console)
](enable-fido-mfa-for-root.md)
+ [

# Enable a virtual MFA device for the root user (console)
](enable-virt-mfa-for-root.md)
+ [

# Enable a hardware TOTP token for the root user (console)
](enable-hw-mfa-for-root.md)

# Enable a passkey or security key for the root user (console)
Enable a passkey or security key

You can configure and enable a passkey for your root user from the AWS Management Console only, not from the AWS CLI or AWS API. <a name="enable_fido_root"></a>

**To enable a passkey or security key for your root user (console)**

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. On the right side of the navigation bar, choose your account name, and then choose **Security credentials**.  
![\[Security credentials in the navigation menu\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-root.shared.console.png)

1. On your root user **My security credentials** page, under **Multi-factor authentication (MFA)**, choose **Assign MFA device**.

1. On the **MFA device name** page, enter a **Device name**, choose **Passkey or Security Key**, and then choose **Next**.

1. On **Set up device**, set up your passkey. Create a passkey with biometric data like your face or fingerprint, with a device pin, or by inserting the FIDO security key into your computer's USB port and tapping it.

1. Follow the instructions on your browser to choose a passkey provider or where you want to store your passkey to use across your devices. 

1. Choose **Continue**.

You have now registered your passkey for use with AWS. The next time you use your root user credentials to sign in, you must authenticate with your passkey to complete the sign-in process.

For help troubleshooting issues with your FIDO security key, see [Troubleshoot Passkeys and FIDO Security Keys](troubleshoot_mfa-fido.md).

# Enable a virtual MFA device for the root user (console)
Enable a virtual MFA device

You can use the AWS Management Console to configure and enable a virtual MFA device for your root user. To enable MFA devices for the AWS account, you must be signed in to AWS using your root user credentials. 

**To configure and enable a virtual MFA device for use with your root user (console)**

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. On the right side of the navigation bar, choose your account name, and choose **Security credentials**.  
![\[Security credentials in the navigation menu\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-root.shared.console.png)

1. In the **Multi-Factor Authentication (MFA)** section, choose **Assign MFA device**.

1. In the wizard, type a **Device name**, choose **Authenticator app**, and then choose **Next**.

   IAM generates and displays configuration information for the virtual MFA device, including a QR code graphic. The graphic is a representation of the secret configuration key that is available for manual entry on devices that do not support QR codes.

1. Open the virtual MFA app on the device. 

   If the virtual MFA app supports multiple virtual MFA devices or accounts, choose the option to create a new virtual MFA device or account.

1. The easiest way to configure the app is to use the app to scan the QR code. If you cannot scan the code, you can type the configuration information manually. The QR code and secret configuration key generated by IAM are tied to your AWS account and cannot be used with a different account. They can, however, be reused to configure a new MFA device for your account in case you lose access to the original MFA device.
   + To use the QR code to configure the virtual MFA device, from the wizard, choose **Show QR code**. Then follow the app instructions for scanning the code. For example, you might need to choose the camera icon or choose a command like **Scan account barcode**, and then use the device's camera to scan the QR code.
   + In the **Set up device** wizard, choose **Show secret key**, and then type the secret key into your MFA app.
**Important**  
Make a secure backup of the QR code or secret configuration key, or make sure that you enable multiple MFA devices for your account. You can register up to **eight** MFA devices of any combination of the [ currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) with your AWS account root user and IAM users. A virtual MFA device might become unavailable, for example, if you lose the smartphone where the virtual MFA device is hosted. If that happens and you are not able to sign in to your account with no additional MFA devices attached to the user or even by [Recovering a root user MFA device](id_credentials_mfa_lost-or-broken.md#root-mfa-lost-or-broken), you will not be able to sign in to your account and you will have to [contact customer service](https://support.aws.amazon.com/#/contacts/aws-mfa-support) to remove MFA protection for the account. 

   The device starts generating six-digit numbers.

1. In the wizard, in the **MFA code 1** box, type the one-time password that currently appears in the virtual MFA device. Wait up to 30 seconds for the device to generate a new one-time password. Then type the second one-time password into the **MFA code 2** box. Choose **Add MFA**. 
**Important**  
Submit your request immediately after generating the code. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device is out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can [resync the device](id_credentials_mfa_sync.md).

The device is ready for use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md).

# Enable a hardware TOTP token for the root user (console)
Enable a hardware TOTP token

You can configure and enable a physical MFA device for your root user from the AWS Management Console only, not from the AWS CLI or AWS API.

**Note**  
You might see different text, such as **Sign in using MFA** and **Troubleshoot your authentication device**. However, the same features are provided. In either case, if you cannot verify your account email address and phone number using alternative factors of authentication, contact [AWS Support](https://aws.amazon.com/forms/aws-mfa-support) to delete your MFA setting.<a name="enable_physical_root"></a>

**To enable a hardware TOTP token for your root user (console)**

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. On the right side of the navigation bar, choose your account name, and then choose **Security credentials**.  
![\[Security credentials in the navigation menu\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-root.shared.console.png)

1. Expand the **Multi-factor authentication (MFA)** section.

1. Choose **Assign MFA device**.

1. In the wizard, type a **Device name**, choose **Hardware TOTP token**, and then choose **Next**.

1. In the **Serial number** box, type the serial number that is found on the back of the MFA device.

1. In the **MFA code 1** box, type the six-digit number displayed by the MFA device. You might need to press the button on the front of the device to display the number.  
![\[IAM Dashboard, MFA Device\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/MFADevice.png)

1. Wait 30 seconds while the device refreshes the code, and then type the next six-digit number into the **MFA code 2** box. You might need to press the button on the front of the device again to display the second number.

1. Choose **Add MFA**. The MFA device is now associated with the AWS account.
**Important**  
Submit your request immediately after generating the authentication codes. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device becomes out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can [resync the device](id_credentials_mfa_sync.md).

   The next time you use your root user credentials to sign in, you must type a code from the MFA device.

# Change the password for the AWS account root user
Change the password

You can change the email address and password from either the [Security Credentials](https://console.aws.amazon.com/iam/home?#security_credential) or the **Account** page. You can also choose **Forgot password?** on the AWS sign-in page to reset your password.

To change the root user's password, you must sign in as the AWS account root user and not as an IAM user. To learn how to reset a *forgotten* root user password, see [Reset a lost or forgotten root user password](reset-root-password.md). 

To protect your password, it's important to follow these best practices:
+ Change your password periodically. 
+ Keep your password private because anyone who knows your password can access your account.
+ Use a different password on AWS than you use on other sites. 
+ Avoid passwords that are easy to guess. These include passwords such as `secret`, `password`, `amazon`, or `123456`. Also avoid things like dictionary words, your name, email address, or other personal information that someone can easily obtain.

**Important**  
AWS accounts managed using AWS Organizations may have [centralized root access](id_root-user.md#id_root-user-access-management) enabled for member accounts. These member accounts do not have root user credentials, can't sign in as a root user, and are prevented from recovering the root user password. Contact your administrator if you need to perform a task that requires root user credentials.

------
#### [ AWS Management Console ]

**To change the password for the root user**
**Minimum permissions**  
To perform the following steps, you must have at least the following IAM permissions:  
You must sign in as the AWS account root user, which requires no additional AWS Identity and Access Management (IAM) permissions. You can't perform these steps as an IAM user or role.

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. In the upper right corner of the console, choose your account name or number, and then select **Security Credentials**.

1. On the **Account** page, next to **Account settings**, choose **Edit**. You are prompted to re-authenticate for security purposes.
**Note**  
If you don't see the **Edit** option, it is likely that you are not signed in as the root user for your account. You can't modify account settings while signed in as an IAM user or role.

1. On the **Update account settings** page, under **Password**, choose **Edit**.

1. On the **Update your password** page, fill out the fields for **Current password**, **New password**, and **Confirm new password**.
**Important**  
Make sure to choose a strong password. Although you can set an account password policy for IAM users, that policy doesn't apply to the root user.

   AWS requires that your password meet the following conditions:
   + It must have a minimum of 8 characters and a maximum of 128 characters.
   + It must include a minimum of three of the following mix of character types: uppercase, lowercase, numbers, and \$1 @ \$1 \$1 % ^ & \$1 () <> [] \$1\$1 \$1 \$1\$1-= symbols.
   + It must not be identical to your AWS account name or email address.

1. Choose **Save changes**.

------
#### [ AWS CLI or AWS SDK ]

This task isn't supported in the AWS CLI or by an API operation from one of the AWS SDKs. You can perform this task only by using the AWS Management Console.

------

# Reset a lost or forgotten root user password


When you first created your AWS account, you provided an email address and password. These are your AWS account root user credentials. If you forget your root user password, you can reset the password from the AWS Management Console.

AWS accounts managed using AWS Organizations may have [centralized root access](id_root-user.md#id_root-user-access-management) enabled for member accounts. These member accounts do not have root user credentials, can't sign in as a root user, and are prevented from recovering the root user password. Contact your administrator if you need to perform a task that requires root user credentials.

**Important**  
**Having trouble signing in to AWS?** Make sure that you're on the correct [AWS sign-in page](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html) for your type of user. If you are the AWS account root user (account owner), you can sign in to AWS using the credentials that you set up when you created the AWS account. If you are an IAM user, your account administrator can give you the credentials that you can use to sign in to AWS. If you need to request support, do not use the feedback link on this page, as the form is received by the AWS Documentation team, not Support. Instead, on the [Contact Us](https://aws.amazon.com/contact-us/) page choose **Still unable to log into your AWS account** and then choose one of the available support options.

**To reset your root user password**

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.
**Note**  
 If you are signed in to the [AWS Management Console](https://console.aws.amazon.com/) with *IAM user* credentials, then you must sign out before you can reset the root user password. If you see the account-specific IAM user sign-in page, choose **Sign-in using root account credentials** near the bottom of the page. If necessary, provide your account email address and choose **Next** to access the **Root user sign in** page.

1. Choose **Forgot your password?**.
**Note**  
If you are an IAM user, this option is not available. The **Forgot your password?** option is only available for the root user account. IAM users must ask their administrator to reset a forgotten password. For more information, see [I forgot my IAM user password for my AWS account](https://docs.aws.amazon.com/signin/latest/userguide/troubleshooting-sign-in-issues.html#troubleshoot-forgot-iam-password). If you sign in through the AWS access portal, see [ Resetting your IAM Identity Center user password](https://docs.aws.amazon.com/singlesignon/latest/userguide/resetpassword-accessportal.html).

1. Provide the email address that is associated with the account. Then provide the CAPTCHA text and choose **Continue**.

1. Check the email that is associated with your AWS account for a message from Amazon Web Services. The email will come from an address ending in `@verify.signin.aws`. Follow the directions in the email. If you don't see the email in your account, check your spam folder. If you no longer have access to the email, see [I don't have access to the email for my AWS account](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-troubleshooting.html#credentials-not-working-console) in the *AWS Sign-In User Guide*.

# Create access keys for the root user


**Warning**  
We strongly recommend that you do **not** create access key pairs for your root user. Because [only a few tasks require the root user](id_root-user.md#root-user-tasks) and you typically perform those tasks infrequently, we recommend signing in to the AWS Management Console to perform the root user tasks. Before creating access keys, review the [alternatives to long-term access keys](security-creds-programmatic-access.md#security-creds-alternatives-to-long-term-access-keys).

Although we don't recommend it, you can create access keys for your root user so that you can run commands in the AWS Command Line Interface (AWS CLI) or use API operations from one of the AWS SDKs using root user credentials. When you create access keys, you create the access key ID and secret access key as a set. During access key creation, AWS gives you one opportunity to view and download the secret access key part of the access key. If you don't download it or if you lose it, you can delete the access key and then create a new one. You can create root user access keys with the console, AWS CLI, or AWS API.

A newly created access key has the status of *active*, which means that you can use the access key for CLI and API calls. You can assign up to two access keys to the root user.

Access keys that are not in use should be inactivated. Once an access key is inactive, you can't use it for API calls. Inactive keys still count toward your limit. You can create or delete an access key any time. However, when you delete an access key, it's gone forever and can't be retrieved.

------
#### [ AWS Management Console ]

**To create an access key for the AWS account root user**
**Minimum permissions**  
To perform the following steps, you must have at least the following IAM permissions:  
You must sign in as the AWS account root user, which requires no additional AWS Identity and Access Management (IAM) permissions. You can't perform these steps as an IAM user or role.

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. In the upper right corner of the console, choose your account name or number and then choose **Security Credentials**. 

1. In the **Access keys** section, choose **Create access key**. If this option is not available, then you already have the maximum number of access keys. You must delete one of the existing access keys before you can create a new key. For more information, see [IAM Object Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities). 

1. On the **Alternatives to root user access keys** page, review the security recommendations. To continue, select the checkbox, and then choose **Create access key**. 

1. On the **Retrieve access key** page, your **Access key** ID is displayed. 

1. Under **Secret access key**, choose **Show** and then copy the access key ID and secret key from your browser window and paste it somewhere secure. Alternatively, you can choose **Download .csv file** which will download a file named `rootkey.csv` that contains the access key ID and the secret key. Save the file somewhere safe.

1. Choose **Done**. When you no longer need the access key [we recommend that you delete it](id_root-user_manage_delete-key.md), or at least consider deactivating it so that no one can misuse it.

------
#### [ AWS CLI & SDKs ]

**To create an access key for the root user**
**Note**  
To run the following command or API operation as the root user, you must already have one active access key pair. If you don't have any access keys, create the first access key using the AWS Management Console. Then, you can use the credentials from that first access key with the AWS CLI to create the second access key, or to delete an access key.
+ AWS CLI: [aws iam create-access-key](https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html)  
**Example**  

  ```
  $ aws iam create-access-key
  {
      "AccessKey": {
          "UserName": "MyUserName",
          "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
          "Status": "Active",
          "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
          "CreateDate": "2021-04-08T19:30:16+00:00"
      }
  }
  ```
+ AWS API: [CreateAccessKey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html) in the *IAM API Reference*. 

------

# Delete access keys for the root user


You can use the AWS Management Console, the AWS CLI or the AWS API to delete the root user access keys.

------
#### [ AWS Management Console ]

**To delete an access key for the root user**
**Minimum permissions**  
To perform the following steps, you must have at least the following IAM permissions:  
You must sign in as the AWS account root user, which requires no additional AWS Identity and Access Management (IAM) permissions. You can't perform these steps as an IAM user or role.

1. Open the [AWS Management Console](https://console.aws.amazon.com/) and sign in using your root user credentials.

   For instructions, see [Sign in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. In the upper right corner of the console, choose your account name or number and then choose **Security Credentials**. 

1. In the **Access keys** section, select the access key that you want to delete, and then, under **Actions**, choose **Delete**.
**Note**  
Alternatively, you can **Deactivate** an access key, instead of permanently deleting it. This way you can resume using it in the future without having to change either the key ID or secret key. While the key is inactive, any attempts to use it in requests to the AWS API fail with the error access denied.

1. On the **Delete <access key ID>** dialog box, choose **Deactivate**, enter the access key ID to confirm you want to delete it, and then choose **Delete**. 

------
#### [ AWS CLI & SDKs ]

**To delete an access key for the root user**
**Minimum permissions**  
To perform the following steps, you must have at least the following IAM permissions:  
You must sign in as the AWS account root user, which requires no additional AWS Identity and Access Management (IAM) permissions. You can't perform these steps as an IAM user or role.
+ AWS CLI: [aws iam delete-access-key](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html)  
**Example**  

  ```
  $ aws iam delete-access-key \
      --access-key-id AKIAIOSFODNN7EXAMPLE
  ```

  This command produces no output when successful.
+ AWS API: [DeleteAccessKey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html) 

------

## Tasks that require root user credentials


We recommend that you [configure an administrative user in AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) to perform daily tasks and access AWS resources. However, you can perform the tasks listed below only when you sign in as the root user of an account.

To simplify managing privileged root user credentials across member accounts in AWS Organizations, you can enable centralized root access to help you centrally secure highly privileged access to your AWS accounts. [Centrally manage root access for member accounts](#id_root-user-access-management) lets you centrally remove and prevent long-term root user credential recovery, improving account security in your organization. After you enable this feature, you can perform the following privileged tasks on member accounts.
+ Remove member account root user credentials to prevent account recovery of the root user. You can also allow password recovery to recover root user credentials for a member account.
+ Remove a misconfigured bucket policy that denies all principals from accessing an Amazon S3 bucket.
+ Delete an Amazon Simple Queue Service resource-based policy that denies all principals from accessing an Amazon SQS queue.

**Account Management Tasks**
+ [Change your AWS account settings.](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-root-user.html) Standalone AWS accounts that are not part of AWS Organizations require root credentials to update the email address, root user password, and root user access keys. Other account settings, such as account name, contact information, alternate contacts, payment currency preference, and AWS Regions, don't require root user credentials.
**Note**  
AWS Organizations, with all features enabled, can be used to manage member account settings centrally from the management account and delegated admin accounts. Authorized IAM users or IAM roles in both the management account and delegated admin accounts can close member accounts and update the root email addresses, account names, contact information, alternate contacts, and AWS Regions of member accounts. 
+ [Close your AWS account.](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/close-account.html) Standalone AWS accounts that are not part of AWS Organizations require root credentials to close the account. With AWS Organizations, you can close the member accounts centrally from the management account and delegated admin accounts.
+ [Restore IAM user permissions.](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-edit.html) If the only IAM administrator accidentally revokes their own permissions, you can sign in as the root user to edit policies and restore those permissions.

**Billing Tasks**
+ [Activate IAM access to the Billing and Cost Management console](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/control-access-billing.html#ControllingAccessWebsite-Activate).
+ Some Billing tasks are limited to the root user. See [Managing an AWS account](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/manage-account-payment.html) in AWS Billing User Guide for more information.
+ View certain tax invoices. An IAM user with the [aws-portal:ViewBilling](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html#user-permissions) permission can view and download VAT invoices from AWS Europe, but not AWS Inc. or Amazon Internet Services Private Limited (AISPL).

**AWS GovCloud (US) Tasks**
+ [Sign up for AWS GovCloud (US)](https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/getting-started-sign-up.html).
+ Request AWS GovCloud (US) account root user access keys from AWS Support.

**Amazon EC2 Task**
+ [Register as a seller](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the Reserved Instance Marketplace.

**AWS KMS Task**
+ In the event that an AWS Key Management Service key becomes unmanageable, an administrator can recover it by contacting Support; however, Support responds to your root user's primary phone number for authorization by confirming the ticket OTP.

**Amazon Mechanical Turk Task**
+  [Link Your AWS account to your MTurk Requester account](https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMechanicalTurkGettingStartedGuide/SetUp.html#accountlinking).

**Amazon Simple Storage Service Tasks**
+ [Configure an Amazon S3 bucket to enable MFA (multi-factor authentication)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/MultiFactorAuthenticationDelete.html).
+ [Edit or delete an Amazon S3 bucket policy that denies all principals](https://aws.amazon.com/premiumsupport/knowledge-center/change-vpc-endpoint-s3-bucket-policy/).

  You can use privileged actions to unlock an Amazon S3 bucket with a misconfigured bucket policy. For details, see [Perform a privileged task on an AWS Organizations member account](id_root-user-privileged-task.md).

**Amazon Simple Queue Service Task**
+ [Edit or delete an Amazon SQS resource-based policy that denies all principals](https://aws.amazon.com/premiumsupport/knowledge-center/sqs-queue-access-issues-deny-policy).

  You can use privileged actions to unlock an Amazon SQS queue with a misconfigured resource-based policy. For details, see [Perform a privileged task on an AWS Organizations member account](id_root-user-privileged-task.md).

## Additional resources


For more information about the AWS root user, see the following resources:
+ For help with root user issues, see [Troubleshoot issues with the root user](troubleshooting_root-user.md).
+ To centrally manage root user email addresses in AWS Organizations, see [Updating the root user email address for a member account](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_update_primary_email.html) in the *AWS Organizations User Guide*.

The following articles provide additional information about working with the root user.
+ [What are some best practices for securing my AWS account and its resources?](https://repost.aws/knowledge-center/security-best-practices)
+ [How can I create an EventBridge event rule to notify me that my root user was used?](https://repost.aws/knowledge-center/root-user-account-eventbridge-rule) 
+ [Monitor and notify on AWS account root user activity](https://aws.amazon.com/blogs/mt/monitor-and-notify-on-aws-account-root-user-activity/) 
+ [Monitor IAM root user activity](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/monitor-iam-root-user-activity.html) 

# IAM users
Users

**Important**  
 IAM [best practices](best-practices.md) recommend that you require human users to use federation with an identity provider to access AWS using temporary credentials instead of using IAM users with long-term credentials. We recommend that you only use IAM users for [specific use cases](gs-identities-iam-users.md) not supported by federated users.

An *IAM user* is an entity that you create in your AWS account. The IAM user represents the human user or workload who uses the IAM user to interact with AWS resources. An IAM user consists of a name and credentials.

An IAM user with administrator permissions is not the same thing as the AWS account root user. For more information about the root user, see [AWS account root user](id_root-user.md).

## How AWS identifies an IAM user


When you create an IAM user, IAM creates these ways to identify that user:
+ A "friendly name" for the IAM user, which is the name that you specified when you created the IAM user, such as `Richard` or `Anaya`. These are the names you see in the AWS Management Console. Because IAM user names appear in Amazon Resource Names (ARNs), we do not recommend including personally identifying information in the IAM name. Refer to [IAM name requirements](reference_iam-quotas.md#reference_iam-quotas-names) for requirements and restrictions for IAM names.
+ An Amazon Resource Name (ARN) for the IAM user. You use the ARN when you need to uniquely identify the IAM user across all of AWS. For example, you could use an ARN to specify the IAM user as a `Principal` in an IAM policy for an Amazon S3 bucket. An ARN for an IAM user might look like the following: 

  `arn:aws:iam::account-ID-without-hyphens:user/Richard`
+ A unique identifier for the IAM user. This ID is returned only when you use the API, Tools for Windows PowerShell, or AWS CLI to create the IAM user; you do not see this ID in the console.

For more information about these identifiers, see [IAM identifiers](reference_identifiers.md).

## IAM users and credentials


You can access AWS in different ways depending on the IAM user credentials:
+ [**Console password**](id_credentials_passwords.md): A password that the IAM user can type to sign in to interactive sessions such as the AWS Management Console. Disabling the password (console access) for an IAM user prevents them from signing in to the AWS Management Console using their sign-in credentials. It does not change their permissions or prevent them from accessing the console using an assumed role. IAM users with console access enabled can also use these same credentials to authenticate for AWS CLI and SDK access using the `aws login` AWS CLI command. These users will need to have [SignInLocalDevelopmentAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/SignInLocalDevelopmentAccess.html) permissions. See [Authentication and access credentials for the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-authentication.html) in the *AWS Command Line Interface User Guide* for more details. 
+ [**Access keys**](id_credentials_access-keys.md): Used to make programmatic calls to AWS. However, there are more secure alternatives to consider before you create access keys for IAM users. For more information, see [Considerations and alternatives for long-term access keys](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#alternatives-to-long-term-access-keys) in the *AWS General Reference*. If the IAM user has active access keys, they continue to function and allow access through the AWS CLI, Tools for Windows PowerShell, AWS API, or the AWS Console Mobile Application.
+ [**SSH keys for use with CodeCommit**](id_credentials_ssh-keys.md): An SSH public key in the OpenSSH format that can be used to authenticate with CodeCommit.
+ [**Server certificates**](id_credentials_server-certs.md): SSL/TLS certificates that you can use to authenticate with some AWS services. We recommend that you use AWS Certificate Manager (ACM) to provision, manage, and deploy your server certificates. Use IAM only when you must support HTTPS connections in a region that is not supported by ACM. To learn which regions support ACM, see [AWS Certificate Manager endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/acm.html) in the *AWS General Reference*.

You can choose the credentials that are right for your IAM user. When you use the AWS Management Console to create an IAM user, you must choose to at least include a console password or access keys. By default, a brand new IAM user created using the AWS CLI or AWS API has no credentials of any kind. You must create the type of credentials for an IAM user based on your use case. 

You have the following options to administer passwords, access keys, and multi-factor authentication (MFA) devices:
+ **[Manage passwords for your IAM users](id_credentials_passwords.md).** Create and change the passwords that permit access to the AWS Management Console. Set a password policy to enforce a minimum password complexity. Allow IAM users to change their own passwords. 
+ **[Manage access keys for your IAM users](id_credentials_access-keys.md).** Create and update access keys for programmatic access to the resources in your account. 
+ **[Enable multi-factor authentication (MFA) for the IAM user](id_credentials_mfa.md).** As a [best practice](best-practices.md), we recommend that you require multi-factor authentication for all IAM users in your account. With MFA, IAM users must provide two forms of identification: First, they provide the credentials that are part of their user identity (a password or access key). In addition, they provide a temporary numeric code that's generated on a hardware device or by an application on a smartphone or tablet.
+ **[Find unused passwords and access keys](id_credentials_finding-unused.md).** Anyone who has a password or access keys for your account or an IAM user in your account has access to your AWS resources. The security [best practice](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) is to remove passwords and access keys when IAM users no longer need them.
+ **[Download a credential report for your account](id_credentials_getting-report.md).** You can generate and download a credential report that lists all IAM users in your account and the status of their various credentials, including passwords, access keys, and MFA devices. For passwords and access keys, the credential report shows how recently the password or access key has been used.

## IAM users and permissions


By default, a new IAM user has no [permissions](access.md) to do anything. They are not authorized to perform any AWS operations or to access any AWS resources. An advantage of having individual IAM users is that you can assign permissions individually to each user. You might assign administrative permissions to a few users, who then can administer your AWS resources and can even create and manage other IAM users. In most cases, however, you want to limit a user's permissions to just the tasks (AWS actions or operations) and resources that are needed for the job. 

Imagine a user named Diego. When you create the IAM user `Diego`, you create a password for him and attach permissions that let him launch a specific Amazon EC2 instance and read (`GET`) information from a table in an Amazon RDS database. For procedures on how to create IAM users and grant them initial credentials and permissions, see [Create an IAM user in your AWS account](id_users_create.md). For procedures on how to change the permissions for existing users, see [Change permissions for an IAM user](id_users_change-permissions.md). For procedures on how to change the user's password or access keys, see [User passwords in AWS](id_credentials_passwords.md) and [Manage access keys for IAM users](id_credentials_access-keys.md).

You can also add a permissions boundary to your IAM users. A permissions boundary is an advanced feature that allows you to use AWS managed policies to limit the maximum permissions that an identity-based policy can grant to an IAM user or role. For more information about policy types and uses, see [Policies and permissions in AWS Identity and Access Management](access_policies.md).

## IAM users and accounts


Each IAM user is associated with one and only one AWS account. Because IAM users are defined within your AWS account, they don't need to have a payment method on file with AWS. Any AWS activity performed by IAM users in your account is billed to your account.

The number and size of IAM resources in an AWS account are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md).

## IAM users as service accounts


An IAM user is a resource in IAM that has associated credentials and permissions. An IAM user can represent a person or an application that uses its credentials to make AWS requests. This is typically referred to as a *service account*. If you choose to use the long-term credentials of an IAM user in your application, **do not embed access keys directly into your application code.** The AWS SDKs and the AWS Command Line Interface allow you to put access keys in known locations so that you do not have to keep them in code. For more information, see [Manage IAM User Access Keys Properly](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html#iam-user-access-keys) in the *AWS General Reference*. Alternatively, and as a best practice, you can [use temporary security credentials (IAM roles) instead of long-term access keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html#use-roles).

# How IAM users sign in to AWS


To sign in to the AWS Management Console as an IAM user, you must provide your account ID or account alias in addition to your user name and password. When your administrator created your IAM user in the console, they should have sent you your sign-in credentials, including your user name and the URL to your account sign-in page that includes your account ID or account alias. 

```
https://My_AWS_Account_ID.signin.aws.amazon.com/console/
```

**Tip**  
To create a bookmark for your account sign-in page in your web browser, you should manually type the sign-in URL for your account in the bookmark entry. Do not use your web browser bookmark feature because redirects can obscure the sign-in URL. 

You can also sign in at the following general sign-in endpoint and type your account ID or account alias manually:

```
[https://console.aws.amazon.com/](https://console.aws.amazon.com/)
```

For convenience, the AWS sign-in page uses a browser cookie to remember the IAM user name and account information. The next time the user goes to any page in the AWS Management Console, the console uses the cookie to redirect the user to the account sign-in page.

You have access only to the AWS resources that your administrator specifies in the policy that is attached to your IAM user identity. To work in the console, you must have permissions to perform the actions that the console performs, such as listing and creating AWS resources. For more information, see [Access management for AWS resources](access.md) and [Example IAM identity-based policies](access_policies_examples.md).

**Note**  
If your organization has an existing identity system, you might want to create a single sign-on (SSO) option. SSO gives users access to the AWS Management Console for your account without requiring them to have an IAM user identity. SSO also eliminates the need for users to sign in to your organization's site and to AWS separately. For more information, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md). 

**Logging sign-in details in CloudTrail**  
If you enable CloudTrail to log sign-in events to your logs, you need to be aware of how CloudTrail chooses where to log the events.
+ If your users sign-in directly to a console, they are redirected to either a global or a regional sign-in endpoint, based on whether the selected service console supports regions. For example, the main console home page supports regions, so if you sign in to the following URL:

  ```
  https://alias.signin.aws.amazon.com/console
  ```

  you are redirected to a regional sign-in endpoint such as `https://us-east-2.signin.aws.amazon.com`, resulting in a regional CloudTrail log entry in the user's region's log:

  On the other hand, the Amazon S3 console does not support regions, so if you sign in to the following URL

  ```
  https://alias.signin.aws.amazon.com/console/s3
  ```

  AWS redirects you to the global sign-in endpoint at `https://signin.aws.amazon.com`, resulting in a global CloudTrail log entry.
+ You can manually request a certain regional sign-in endpoint by signing in to the region-enabled main console home page using a URL syntax like the following:

  ```
  https://alias.signin.aws.amazon.com/console?region=ap-southeast-1
  ```

  AWS redirects you to the `ap-southeast-1` regional sign-in endpoint and results in a regional CloudTrail log event.

For more information about CloudTrail and IAM, see [Logging IAM events with CloudTrail](https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html).

If users need programmatic access to work with your account, you can create an access key pair (an access key ID and a secret access key) for each user. However, there are more secure alternatives to consider before you create access keys for users. For more information, see [Considerations and alternatives for long-term access keys](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#alternatives-to-long-term-access-keys) in the *AWS General Reference*.

## Additional resources


The following resources can help you learn more about AWS sign-in.
+ The [AWS Sign-In User Guide](https://docs.aws.amazon.com/signin/latest/userguide/what-is-sign-in.html) helps you understand the different ways that you can sign in to Amazon Web Services (AWS), depending on what type of user you are.
+ You can sign in up to five different identities simultaneously in a single web browser in the AWS Management Console. For details, see [Signing in to multiple accounts](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/multisession.html) in the *AWS Management Console Getting Started Guide*.

# MFA enabled sign-in


Users who are configured with [multi-factor authentication (MFA)](id_credentials_mfa.md) devices must use their MFA devices to sign in to the AWS Management Console. After the user enters their sign-in credentials, AWS checks the user's account to see if MFA is required for that user. 

**Important**  
If you use access key and secret key credentials for direct AWS Management Console access with the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API call, MFA will NOT be required. For more information, see [Using access keys and secret key credentials for console access](securing_access-keys.md#console-access-security-keys).

The following topics provide information on how users complete signing in when MFA is required. 

**Topics**
+ [

## Multiple MFA devices enabled
](#console_sign-in-multiple-mfa)
+ [

## FIDO security key
](#console_sign-in-mfa-fido)
+ [

## Virtual MFA device
](#console_sign-in-mfa-virtual)
+ [

## Hardware TOTP token
](#console_sign-in-mfa-hardware)

## Multiple MFA devices enabled


If a user signs in to the AWS Management Console as an AWS account root user or IAM user with multiple MFA devices enabled for that account, they only need to use one MFA device to sign in. After the user authenticates with the user’s password, they select which MFA device type they would like to use to finish authenticating. Then the user is prompted to authenticate with the type of device that they selected. 

## FIDO security key


If MFA is required for the user, a second sign-in page appears. The user needs to tap the FIDO security key.

**Note**  
Google Chrome users should not choose any of the available options on the pop-up that asks to **Verify your identity with amazon.com**. You only need to tap on the security key.

Unlike other MFA devices, FIDO security keys do not go out of sync. Administrators can deactivate a FIDO security key if it's lost or broken. For more information, see [Deactivating MFA devices (console)](id_credentials_mfa_disable.md#deactive-mfa-console).

For information on browsers that support WebAuthn and FIDO-compliant devices that AWS supports, see [Supported configurations for using passkeys and security keys](id_credentials_mfa_fido_supported_configurations.md).

## Virtual MFA device


If MFA is required for the user, a second sign-in page appears. In the **MFA code** box, the user must enter the numeric code provided by the MFA application.

If the MFA code is correct, the user can access the AWS Management Console. If the code is incorrect, the user can try again with another code. 

A virtual MFA device can go out of sync. If a user cannot sign in to the AWS Management Console after several tries, the user is prompted to synchronize the virtual MFA device. The user can follow the on-screen prompts to synchronize the virtual MFA device. For information about how you can synchronize a device on behalf of a user in your AWS account, see [Resynchronize virtual and hardware MFA devices](id_credentials_mfa_sync.md). 

## Hardware TOTP token


If MFA is required for the user, a second sign-in page appears. In the **MFA code** box, the user must enter the numeric code provided by a hardware TOTP token. 

If the MFA code is correct, the user can access the AWS Management Console. If the code is incorrect, the user can try again with another code. 

A hardware TOTP token can go out of sync. If a user can't sign in to the AWS Management Console after several tries, the user is prompted to synchronize the MFA token device. The user can follow the on-screen prompts to synchronize the MFA token device. For information about how you can synchronize a device on behalf of a user in your AWS account, see [Resynchronize virtual and hardware MFA devices](id_credentials_mfa_sync.md). 

# Create an IAM user in your AWS account
Create a user

**Important**  
 IAM [best practices](best-practices.md) recommend that you require human users to use federation with an identity provider to access AWS using temporary credentials instead of using IAM users with long-term credentials. We recommend that you only use IAM users for [specific use cases](gs-identities-iam-users.md) not supported by federated users.

The process of creating an IAM user and enabling that user to perform tasks consists of the following steps:

1. Create the [user in the AWS Management Console, the AWS CLI](getting-started-workloads.md), Tools for Windows PowerShell, or using an AWS API operation. If you create the user in the AWS Management Console, then steps 1–4 are handled automatically, based on your choices. If you create the IAM users programmatically, then you must perform each of those steps individually.

1. Create credentials for the user, depending on the type of access the user requires:
   + **Enable console access – *optional***: If the user needs to access the AWS Management Console, [create a password for the user](id_credentials_passwords_admin-change-user.md). Disabling console access for a user prevents them from signing in to the AWS Management Console using their user name and password. It does not change their permissions or prevent them from accessing the console using an assumed role.
**Tip**  
Create only the credentials that the user needs. For example, for a user who requires access only through the AWS Management Console, do not create access keys.

1. Give the user permissions to perform the required tasks. We recommend that you put your IAM users in groups and manage permissions through policies that are attached to those groups. However, you can also grant permissions by attaching permissions policies directly to the user. If you use the console to add the user, you can copy the permissions from an existing user to the new user.

   You can also add a [permissions boundary](access_policies_boundaries.md) to limit the user’s permissions by specifying a policy that defines the maximum permissions that the user can have. Permissions boundaries don't grant any permissions.

   For instructions on creating a custom permission policy to use to either grant permissions or set a permissions boundary, see [Define custom IAM permissions with customer managed policies](access_policies_create.md).

1. (Optional) Add metadata to the user by attaching tags. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Provide the user with the necessary sign-in information. This includes the password and the console URL for the account sign-in page where the user provides those credentials. For more information, see [How IAM users sign in to AWS](id_users_sign-in.md).

1. (Optional) Configure [multi-factor authentication (MFA)](id_credentials_mfa.md) for the user. MFA requires the user to provide a one-time-use code each time he or she signs into the AWS Management Console.

1. (Optional) Give IAM users permissions to manage their own security credentials. (By default, IAM users do not have permissions to manage their own credentials.) For more information, see [Permit IAM users to change their own passwords](id_credentials_passwords_enable-user-change.md).
**Note**  
If you use the console to create the user and you select **User must create a new password at next sign-in (recommended)**, the user has the required permissions.

For information about the permissions that you need in order to create a user, see [Permissions required to access IAM resources](access_permissions-required.md).

For instructions on creating IAM users for specific use cases, see the following topics:
+ [Create an IAM user for emergency access](getting-started-emergency-iam-user.md)
+ [Create an IAM user for workloads that can't use IAM roles](getting-started-workloads.md)

# View IAM users


You can list the IAM users in your AWS account or in a specific IAM group, and list all the IAM groups that a user is in. For information about the permissions that you need in order to list users, see [Permissions required to access IAM resources](access_permissions-required.md). 

## To list all the IAM users in your account


------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**. 

The console displays the IAM users in your AWS account.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam list-users](https://docs.aws.amazon.com/cli/latest/reference/iam/list-users.html)`

------
#### [ API ]

Call the following operation:
+ `[ListUsers](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUsers.html)` 

------

## To list the IAM users in an IAM group


------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **User groups**.

1. Choose the name of the user group. 

The IAM users that are members of the group are listed on the **Users** tab.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam get-group](https://docs.aws.amazon.com/cli/latest/reference/iam/get-group.html)`

------
#### [ API ]

Call the following operation:
+ `[GetGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetGroup.html)` 

------

## To list all the IAM groups that a user is in


------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user. 

1. Select the **Groups** tab to display the list of groups that include the current user.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam list-groups-for-user](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups-for-user.html)`

------
#### [ API ]

Call the following operation:
+ `[ListGroupsForUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html)` 

------

## Next steps


Once you have a list of your IAM users, you can rename, delete, or deactivate an IAM user using the following procedures.
+ [Rename an IAM user](id_users_rename.md)
+ [Remove or deactivate an IAM user](id_users_remove.md)

# Rename an IAM user
Rename a user

**Note**  
As a [best practice](best-practices.md), we recommend that you require human users to use federation with an identity provider to access AWS using temporary credentials. If you follow the best practices, you are not managing IAM users and groups. Instead, your users and groups are managed outside of AWS and are able to access AWS resources as a *federated identity*. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. Federated identities use the groups defined by their identity provider. If you are using AWS IAM Identity Center, see [Manage identities in IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/manage-your-identity-source-sso.html) in the *AWS IAM Identity Center User Guide* for information about creating users and groups in IAM Identity Center.

Amazon Web Services offers multiple tools for managing the IAM users in your AWS account. You can list the IAM users in your account or in a user group, or list all IAM groups that a user is a member of. You can rename or change the path of an IAM user. If you are moving to using federated identities instead of IAM users, you can delete an IAM user from your AWS account, or deactivate the user.

For more information about adding, changing, or removing managed policies for an IAM user, see [Change permissions for an IAM user](id_users_change-permissions.md). For information about managing inline policies for IAM users, see [Adding and removing IAM identity permissions](access_policies_manage-attach-detach.md), [Edit IAM policies](access_policies_manage-edit.md), and [Delete IAM policies](access_policies_manage-delete.md). As a best practice, use managed policies instead of inline policies. *AWS managed policies* grant permissions for many common use cases. Keep in mind that AWS managed policies might not grant least-privilege permissions for your specific use cases because they are available for use by all AWS customers. As a result, we recommend that you reduce permissions further by defining [customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#customer-managed-policies) that are specific to your use cases. For more information, see [AWS managed policies](access_policies_managed-vs-inline.md#aws-managed-policies). For more information about AWS managed policies that are designed for specific job functions, see [AWS managed policies for job functions](access_policies_job-functions.md).

To learn about validating IAM policies, see [IAM policy validation](access_policies_policy-validator.md).

**Tip**  
[IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) can analyze the services and actions that your IAM roles use, and then generate a fine-grained policy that you can use. After you test each generated policy, you can deploy the policy to your production environment. This ensures that you grant only the required permissions to your workloads. For more information about policy generation, see [IAM Access Analyzer policy generation](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html).

For information about managing IAM user passwords, see [Manage passwords for IAM users](id_credentials_passwords_admin-change-user.md).

## Renaming an IAM user


To change a user's name or path, you must use the AWS CLI, Tools for Windows PowerShell, or AWS API. There is no option in the console to rename a user. For information about the permissions that you need in order to rename a user, see [Permissions required to access IAM resources](access_permissions-required.md). 

When you change a user's name or path, the following happens: 
+ Any policies attached to the user stay with the user under the new name.
+ The user stays in the same IAM groups under the new name.
+ The unique ID for the user remains the same. For more information about unique IDs, see [Unique identifiers](reference_identifiers.md#identifiers-unique-ids).
+ Any resource or role policies that refer to the user *as a principal* (the user is being granted access) are automatically updated to use the new name or path. For example, any queue-based policies in Amazon SQS or resource-based policies in Amazon S3 are automatically updated to use the new name and path. 

IAM does not automatically update policies that refer to the user *as a resource* to use the new name or path; you must manually do that. For example, imagine that user `Richard` has a policy attached to him that lets him manage his security credentials. If an administrator renames `Richard` to `Rich`, the administrator also needs to update that policy to change the resource from this:

```
arn:aws:iam::111122223333:user/division_abc/subdivision_xyz/Richard
```

to this:

```
arn:aws:iam::111122223333:user/division_abc/subdivision_xyz/Rich
```

This is true also if an administrator changes the path; the administrator needs to update the policy to reflect the new path for the user. 

### To rename a user

+ AWS CLI: [aws iam update-user](https://docs.aws.amazon.com/cli/latest/reference/iam/update-user.html)
+ AWS API: [UpdateUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateUser.html) 

# Remove or deactivate an IAM user
Remove a user

[Best practices](best-practices.md#remove-credentials) recommend that you remove unused IAM users from your AWS account. If you want to retain the IAM users credentials for future use, instead of deleting them from the account you can deactivate the user's access. For more information, see [Deactivating an IAM user](#id_users_deactivating).

**Warning**  
Once an IAM user and its access keys are deleted, they cannot be restored or recovered.

## Prerequisite – View IAM user access


Before you remove a user, review their recent service-level activity. This helps prevent removing access from a principal (person or application) who is using it. For more information about viewing last accessed information, see [Refine permissions in AWS using last accessed information](access_policies_last-accessed.md).

## Removing an IAM user (console)


When you use the AWS Management Console to remove an IAM user, IAM automatically deletes the following associated information: 
+ The IAM user identifier
+ Any group memberships—that is, the IAM user is removed from any groups that the IAM user was a member of
+ Any password associated with the IAM user 
+ All inline policies embedded in the IAM user (policies that were applied to the IAM user using user group permissions are not affected) 
**Note**  
IAM removes any managed policies attached to the IAM user when you delete the user, but does not delete managed policies. 
+ Any associated MFA device

### To remove an IAM user (console)


------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**, and then select the checkbox next to the IAM user name that you want to delete. 

1. At the top of the page, choose **Delete**.
**Note**  
If any of the users have active access keys, you must deactivate the access keys before deleting the users. For more information, see [To deactivate an access key for an IAM user](access-keys-admin-managed.md#admin-deactivate-access-key).

1. In the confirmation dialog box, enter the username in the text input field to confirm the deletion of the user. Choose **Delete**. 

The console displays a status notification that the IAM user was deleted.

------

## Deleting an IAM user (AWS CLI)


Unlike the AWS Management Console, when you delete a IAM user with the AWS CLI, you must delete the items attached to the IAM user manually. This procedure illustrates the process. 

**To delete an IAM user from your AWS account (AWS CLI)**

1. Delete the user's password, if the user has one.

   `[aws iam delete-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-login-profile.html)`

1. Delete the user's access keys, if the user has them.

   `[aws iam list-access-keys](https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html)` (to list the user's access keys) and `[aws iam delete-access-key](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html)`

1. Delete the user's signing certificate. Note that when you delete a security credential, it's gone forever and can't be retrieved.

   `[aws iam list-signing-certificates](https://docs.aws.amazon.com/cli/latest/reference/iam/list-signing-certificates.html)` (to list the user's signing certificates) and `[aws iam delete-signing-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-signing-certificate.html)`

1. Delete the user's SSH public key, if the user has them.

   `[aws iam list-ssh-public-keys](https://docs.aws.amazon.com/cli/latest/reference/iam/list-ssh-public-keys.html)` (to list the user's SSH public keys) and `[aws iam delete-ssh-public-key](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-ssh-public-key.html)`

1. Delete the user's Git credentials.

   `[aws iam list-service-specific-credentials](https://docs.aws.amazon.com/cli/latest/reference/iam/list-service-specific-credentials.html)` (to list the user's git credentials) and `[aws iam delete-service-specific-credential](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-service-specific-credential.html)`

1. Deactivate the user's multi-factor authentication (MFA) device, if the user has one.

   `[aws iam list-mfa-devices](https://docs.aws.amazon.com/cli/latest/reference/iam/list-mfa-devices.html)` (to list the user's MFA devices), `[aws iam deactivate-mfa-device](https://docs.aws.amazon.com/cli/latest/reference/iam/deactivate-mfa-device.html)` (to deactivate the device), and `[aws iam delete-virtual-mfa-device](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-virtual-mfa-device.html)` (to permanently delete a virtual MFA device) 

1. Delete the user's inline policies. 

   `[aws iam list-user-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-user-policies.html)` (to list the inline policies for the user) and [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-user-policy.html) (to delete the policy) 

1. Detach any managed policies that are attached to the user. 

   `[aws iam list-attached-user-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-user-policies.html)` (to list the managed policies attached to the user) and [https://docs.aws.amazon.com/cli/latest/reference/iam/detach-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/detach-user-policy.html) (to detach the policy) 

1. Remove the user from any IAM groups. 

   `[aws iam list-groups-for-user](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups-for-user.html)` (to list the IAM groups to which the user belongs) and `[aws iam remove-user-from-group](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-user-from-group.html)` 

1. Delete the user.

   `[aws iam delete-user](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-user.html)` 

## Deactivating an IAM user


You might need to deactivate an IAM user while they are temporarily away from your company. You can leave their IAM user credentials in place and still block their AWS access.

To deactivate a user, create and attach a policy to deny the user access to AWS. You can restore the user's access later.

Here are two examples of deny policies that you can attach to a user to deny their access.

The following policy does not include a time limit. You must remove the policy to restore the user's access.

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

****  

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

------

The following policy includes a condition that starts the policy on December 24, 2024 at 11:59 PM (UTC) and ends it on February 28, 2025 at 11:59 PM (UTC).

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
      {
        "Effect": "Deny",
        "Action": "*",
        "Resource": "*",
        "Condition": {
          "DateGreaterThan": {"aws:CurrentTime": "2024-12-24T23:59:59Z"},
          "DateLessThan": {"aws:CurrentTime": "2025-02-28T23:59:59Z"}
          }
       }
   ]
}
```

------

# Control IAM user access to the AWS Management Console
Control user access to the console

IAM users with permission who sign in to your AWS account through the AWS Management Console can access your AWS resources. The following list shows the ways that you can grant IAM users access to your AWS account resources through the AWS Management Console. It also shows how IAM users can access other AWS account features through the AWS website.

**Note**  
There is no charge to use IAM.

**The AWS Management Console**  
You create a password for each IAM user who needs access to the AWS Management Console. Users access the console through your IAM-enabled AWS account sign-in page. For information about accessing the sign-in page, see [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*. For information about creating passwords, see [User passwords in AWS](id_credentials_passwords.md).  
You can prevent an IAM user from accessing the AWS Management Console by removing their password. This prevents them from signing into the AWS Management Console using their sign-in credentials. It does not change their permissions or prevent them from accessing the console using an assumed role. If the user has active access keys, they continue to function and allow access through the AWS CLI, Tools for Windows PowerShell, AWS API, or the AWS Console Mobile Application.

**Your AWS resources, such as Amazon EC2 instances, Amazon S3 buckets, and so on**  
Even if your IAM users have passwords, they still need permission to access your AWS resources. When you create an IAM user, that user has no permissions by default. To give your IAM users the permissions they need, you attach policies to them. If you have many IAM users who perform the same tasks with the same resources, you can assign those IAM users to a group. Then assign the permissions to that group. For information about creating IAM users and groups, see [IAM Identities](id.md). For information about using policies to set permissions, see [Access management for AWS resources](access.md).

**AWS Discussion Forums**  
Anyone can read the posts on the [AWS Discussion Forums](https://forums.aws.amazon.com/). Users who want to post questions or comments to the AWS Discussion Forum can do so using their user name. The first time a user posts to the AWS Discussion Forum, the user is prompted to enter a nickname and email address. Only that user can use that nickname in the AWS Discussion Forums. 

**Your AWS account billing and usage information**  
You can grant users access your AWS account billing and usage information. For more information, see [ Controlling Access to Your Billing Information](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/control-access-billing.html) in the *AWS Billing User Guide*. 

**Your AWS account profile information**  
Users cannot access your AWS account profile information.

**Your AWS account security credentials**  
Users cannot access your AWS account security credentials.

**Note**  
IAM policies control access regardless of the interface. For example, you could provide a user with a password to access the AWS Management Console. The policies for that user (or any groups the user belongs to) would control what the user can do in the AWS Management Console. Or, you could provide the user with AWS access keys for making API calls to AWS. The policies would control which actions the user could call through a library or client that uses those access keys for authentication.

# Change permissions for an IAM user
Change user permissions

You can change the permissions for an IAM user in your AWS account by changing its group memberships, by copying permissions from an existing user, by attaching policies directly to a user, or by setting a [permissions boundary](access_policies_boundaries.md). A permissions boundary controls the maximum permissions that a user can have. Permissions boundaries are an advanced AWS feature.

For information about the permissions that you need in order to modify the permissions for a user, see [Permissions required to access IAM resources](access_permissions-required.md).

**Topics**
+ [

## View user access
](#users-modify_prerequisites)
+ [

## Generate a policy based on a user's access activity
](#users_change_permissions-gen-policy)
+ [

## Adding permissions to a user (console)
](#users_change_permissions-add-console)
+ [

## Changing permissions for a user (console)
](#users_change_permissions-change-console)
+ [

## To remove a permissions policy from a user (console)
](#users_change_permissions-remove-policy-console)
+ [

## To remove the permissions boundary from a user (console)
](#users_change_permissions-remove-boundary-console)
+ [

## Adding and removing a user's permissions (AWS CLI or AWS API)
](#users_change_permissions-add-programmatic)

## View user access


Before you change the permissions for a user, you should review its recent service-level activity. This is important because you don't want to remove access from a principal (person or application) who is using it. For more information about viewing last accessed information, see [Refine permissions in AWS using last accessed information](access_policies_last-accessed.md).

## Generate a policy based on a user's access activity


You might sometimes grant permissions to an IAM entity (user or role) beyond what they require. To help you refine the permissions that you grant, you can generate an IAM policy that is based on the access activity for an entity. IAM Access Analyzer reviews your AWS CloudTrail logs and generates a policy template that contains the permissions that have been used by the entity in your specified date range. You can use the template to create a managed policy with fine-grained permissions and then attach it to the IAM entity. That way, you grant only the permissions that the user or role needs to interact with AWS resources for your specific use case. To learn more, see [IAM Access Analyzer policy generation](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html).

## Adding permissions to a user (console)


IAM offers three ways to add permissions policies to a user:
+ **Add the IAM user to an IAM group** – Make the user a member of a group. The policies from the group are attached to the user.
+ **Copy permissions from an existing IAM user** – Copy all group memberships, attached managed policies, inline policies, and any existing permissions boundaries from the source user.
+ **Attach policies directly to the IAM user** – Attach a managed policy directly to the user. For easier permissions management, attach your policies to a group and then make IAM users members of the appropriate groups.

**Important**  
If the user has a permissions boundary, then you cannot add more permissions to the user than are allowed by the permissions boundary.

### To add permissions by adding the IAM user to a group


Adding an IAM user to an IAM group updates the user's permissions with the permissions defined for the group immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user. 

1. Select the **Groups** tab to display the list of groups that include the current user.

1. Choose **Add user to groups**. 

1. Select the checkbox for each group that you want the user to join. The list shows each group's name and the policies that the user receives if made a member of that group.

1. (Optional) You can choose **Create group** to define a new group. This is useful if you want to add the user to a group with different attached policies than the existing groups:

   1. In the new tab, for **User group name**, type a name for your new group.
**Note**  
The number and size of IAM resources in an AWS account are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md). Group names can be a combination of up to 128 letters, digits, and these characters: plus (\$1), equal (=), comma (,), period (.), at sign (@), and hyphen (-). Names must be unique within an account. They are not distinguished by case. For example, you cannot create two groups named *TESTGROUP* and *testgroup*.

   1. Select one or more checkboxes for the managed policies that you want to attach to the group. You can also create a new managed policy by choosing **Create policy**. If you do, return to this browser tab or window when the new policy is done; choose **Refresh**; and then choose the new policy to attach it to your group. For more information, see [Define custom IAM permissions with customer managed policies](access_policies_create.md).

   1. Choose **Create user group**.

   1. Return to the original tab, refresh your list of groups. Then select the checkbox for your new group.

1. Choose **Add user to group(s)**.

The console displays a status message informing you that the user has been added to the groups you specified.

------

### To add permissions by copying from another IAM user


If you choose to add permissions to an IAM user by copying permissions, IAM copies all group memberships, attached managed policies, inline policies, and any existing permissions boundaries from the specified user and applies them immediately to the currently selected user.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user. 

1. On the **Permissions** tab choose and select **Add permissions**.

1. On the **Add permissions** page, choose **Copy permissions**. The list displays available IAM users along with their group memberships and attached policies. 

1. Select the radio button next to the user whose permissions you want to copy. 

1. Choose **Next** to see the list of changes that are to be made to the user. Then choose **Add permissions**.

The console displays a status message informing you that the permissions were copied from the IAM user you specified.

------

### To add permissions by attaching policies directly to the IAM user


You can attach a managed policy directly to an IAM user. The updated permissions are applied immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user. 

1. On the **Permissions** tab, choose and select **Add permissions**.

1. On the **Add permissions** page, choose **Attach policies directly**. The **Permissions policies** list displays available policies along with their policy types and attached entities. 

1. Select the radio button next to the **Policy name** you want to attach. 

1. Choose **Next** to see the list of changes that are to be made to the user. Then choose **Add permissions**.

The console displays a status message informing you that the policy was added to the IAM user you specified.

------

### To set the permissions boundary for an IAM user


A permissions boundary is an advanced feature for managing permissions in AWS that is used to set the maximum permissions that an IAM user can have. Setting a permissions boundary immediately restricts the IAM user permissions to the boundary, regardless of the other permissions granted.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user whose permissions boundary you want to change. 

1. Choose the **Permissions** tab. If necessary, open the **Permissions boundary** section and then choose **Set permissions boundary**.

1. On the **Set permissions boundary** page, under **Permissions policies** select the policy that you want to use for the permissions boundary.

1. Choose **Set boundary**.

The console displays a status message informing you that the permissions boundary has been added.

------

## Changing permissions for a user (console)


IAM allows you to change the permissions that are associated with a user in the following ways:
+ **Edit a permissions policy** – Edit a user's inline policy, the inline policy of the user's group, or edit a managed policy that is attached to the user directly or from a group. If the user has a permissions boundary, then you cannot provide more permissions than are allowed by the policy that was used as the user's permissions boundary.
+ **Changing the permissions boundary** – Change the policy that is used as the permissions boundary for the user. This can expand or restrict the maximum permissions that a user can have. 

### Editing a permissions policy attached to a user


Changing permissions updates the user's access immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user whose permissions boundary you want to change. 

1. Choose the **Permissions** tab. If necessary, open the **Permissions boundary** section.

1. Choose the name of the policy that you want to edit to view details about the policy. Choose the **Entities attached** tab to view other entities (IAM users, groups, and roles) that might be affected if you edit the policy. 

1. Choose the **Permissions** tab and review the permissions granted by the policy. To make changes to the permissions, choose **Edit**. 

1. Edit the policy and resolve any [policy validation](access_policies_policy-validator.md) recommendations. For more information, see [Edit IAM policies](access_policies_manage-edit.md).

1. Choose **Next**, review the policy summary, and then choose **Save changes**.

The console displays a status message informing you that the policy has been updated.

------

### To change the permissions boundary for a user


Changing a permissions boundary updates the user's access immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user whose permissions boundary you want to change. 

1. Choose the **Permissions** tab. If necessary, open the **Permissions boundary** section and then choose **Change boundary**.

1. Select the policy that you want to use for the permissions boundary.

1. Choose **Set boundary**.

The console displays a status message informing you that the permissions boundary has been changed.

------

## To remove a permissions policy from a user (console)


Removing a permissions policy updates the user's access immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. Choose the name of the user whose permissions policies you want to remove. 

1. Choose the **Permissions** tab. 

1. If you want to remove permissions by removing an existing policy, view the **Attached via** column to understand how the user is getting that policy before choosing **Remove** to remove the policy:
   + If the policy applies because of group membership, then choosing **Remove** removes the user from the group. Remember that you might have multiple policies attached to a single group. If you remove a user from a group, the user loses access to *all* policies that it received through that group membership.
   + If the policy is a managed policy attached directly to the user, then choosing **Remove** detaches the policy from the user. This does not affect the policy itself or any other entity that the policy might be attached to.
   + If the policy is an inline embedded policy, then choosing **Remove** removes the policy from IAM. Inline policies that are attached directly to a user exist only on that user.

If the policy was granted to the user through a group membership, the console displays a status message informing you that the IAM user was removed from the IAM group. If the policy directly attached or inline, the status message informs you that the policy has been removed.

------

## To remove the permissions boundary from a user (console)


Removing the permissions boundary updates the user's access immediately.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. In the **Users** list, choose the name of the IAM user whose permissions boundary you want to remove. 

1. Choose the **Permissions** tab. If necessary, open the **Permissions boundary** section.

1.  Choose **Change boundary**. To confirm that you want to remove the permissions boundary, in the confirmation dialog, choose **Remove boundary**.

The console displays a status message informing you that the permissions boundary has been removed.

------

## Adding and removing a user's permissions (AWS CLI or AWS API)


To add or remove permissions programmatically, you must add or remove the group memberships, attach or detach the managed policies, or add or delete the inline policies. For more information, see the following topics:
+ [Edit users in IAM groups](id_groups_manage_add-remove-users.md)
+ [Adding and removing IAM identity permissions](access_policies_manage-attach-detach.md)

# User passwords in AWS
User passwords

You can manage passwords for IAM users in your account. IAM users need passwords in order to access the AWS Management Console. Users do not need passwords to access AWS resources programmatically by using the AWS CLI, Tools for Windows PowerShell, the AWS SDKs or APIs. For those environments, you have the option of assigning IAM users [access keys](id_credentials_access-keys.md). However, there are other more secure alternatives to access keys that we recommend you consider first. For more information, see [AWS security credentials](security-creds.md).

**Note**  
If one of your IAM users lose or forget their password, you *cannot* retrieve them from IAM. Depending on your settings, either the user or the administrator must create a new password.

**Topics**
+ [

# Set an account password policy for IAM users
](id_credentials_passwords_account-policy.md)
+ [

# Manage passwords for IAM users
](id_credentials_passwords_admin-change-user.md)
+ [

# Permit IAM users to change their own passwords
](id_credentials_passwords_enable-user-change.md)
+ [

# How an IAM user changes their own password
](id_credentials_passwords_user-change-own.md)

# Set an account password policy for IAM users
Set a password policy

You can set a custom password policy on your AWS account to specify complexity requirements and mandatory rotation periods for your IAM users' passwords. If you don't set a custom password policy, IAM user passwords must meet the default AWS password policy. For more information, see [Custom password policy options](#password-policy-details).

**Topics**
+ [

## Rules for setting a password policy
](#password-policy-rules)
+ [

## Permissions required to set a password policy
](#default-policy-permissions-required)
+ [

## Default password policy
](#default-policy-details)
+ [

## Custom password policy options
](#password-policy-details)
+ [

## To set a password policy (console)
](#IAMPasswordPolicy)
+ [

## To change a password policy (console)
](#id_credentials_passwords_account-policy-section-1)
+ [

## To delete a custom password policy (console)
](#id_credentials_passwords_account-policy-section-2)
+ [

## Setting a password policy (AWS CLI)
](#PasswordPolicy_CLI)
+ [

## Setting a password policy (AWS API)
](#PasswordPolicy_API)

## Rules for setting a password policy


The IAM password policy does not apply to the AWS account root user password or IAM user access keys. If a password expires, the IAM user can't sign in to the AWS Management Console but can continue to use their access keys.

When you create or change a password policy, most of the password policy settings are enforced the next time your users change their passwords. However, some of the settings are enforced immediately. For example: 
+ When the minimum length and character type requirements change, these settings are enforced the next time that your users change their passwords. Users are not forced to change their existing passwords, even if the existing passwords do not adhere to the updated password policy.
+ When you set a password expiration period, the expiration period is enforced immediately. For example, assume that you set a password expiration period of 90 days. In that case, the password expires for all IAM users whose existing password is older than 90 days. Those users are required to change their password the next time that they sign in.

You can't create a "lockout policy" to lock a user out of the account after a specified number of failed sign-in attempts. For enhanced security, we recommend that you combine a strong password policy with multi-factor authentication (MFA). For more information about MFA, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md).

## Permissions required to set a password policy


You must configure permissions to allow an IAM entity (user or role) to view or edit their account password policy. You can include the following password policy actions in an IAM policy: 
+ `iam:GetAccountPasswordPolicy` – Allows the entity to view the password policy for their account
+ `iam:DeleteAccountPasswordPolicy` – Allows the entity to delete the custom password policy for their account and revert to the default password policy
+ `iam:UpdateAccountPasswordPolicy` – Allows the entity to create or change the custom password policy for their account

The following policy allows full access to view and edit the account password policy. To learn how to create an IAM policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "FullAccessPasswordPolicy",
            "Effect": "Allow",
            "Action": [
                "iam:GetAccountPasswordPolicy",
                "iam:DeleteAccountPasswordPolicy",
                "iam:UpdateAccountPasswordPolicy"
            ],
            "Resource": "*"
        }
    ]
}
```

------

For information about the permissions required for an IAM user to change their own password, see [Permit IAM users to change their own passwords](id_credentials_passwords_enable-user-change.md).

## Default password policy


If an administrator does not set a custom password policy, IAM user passwords must meet the default AWS password policy.

The default password policy enforces the following conditions:
+ Minimum password length of 8 characters and a maximum length of 128 characters
+ Minimum of three of the following mix of character types: uppercase, lowercase, numbers, and non-alphanumeric character (`! @ # $ % ^ & * ( ) _ + - = [ ] { } | '`)
+ Not be identical to your AWS account name or email address
+ Never expire password

## Custom password policy options


When you configure a custom password policy for your account, you can specify the following conditions:
+ **Password minimum length** – You can specify a minimum of 6 characters and a maximum of 128 characters.
+ **Password strength** – You can select any of the following checkboxes to define the strength of your IAM user passwords:
  + Require at least one uppercase letter from the Latin alphabet (A–Z)
  + Require at least one lowercase letter from the Latin alphabet (a–z)
  + Require at least one number
  + Require at least one nonalphanumeric character `! @ # $ % ^ & * ( ) _ + - = [ ] { } | '` 
+ **Turn on password expiration** – You can select and specify a minimum of 1 and a maximum of 1,095 days that IAM user passwords are valid after they are set. For example, if you specify an expiration of 90 days, it immediately impacts all of your users. For users with passwords older than 90 days, when they log into the console after the change, they must set a new password. Users with passwords 75-89 days old receive an AWS Management Console warning about their password expiration. IAM users can change their password at any time if they have permission. When they set a new password, the expiration period for that password starts over. An IAM user can have only one valid password at a time.
+ **Password expiration requires administrator reset** – Select this option to prevent IAM users from using the AWS Management Console to update their own passwords after the password expires. Before you select this option, confirm that your AWS account has more than one user with administrative permissions to reset IAM user passwords. Administrators with `iam:UpdateLoginProfile` permission can reset IAM user passwords. IAM users with `iam:ChangePassword` permission and active access keys can reset their own IAM user console password programmatically. If you clear this checkbox, IAM users with expired passwords must still set a new password before they can access the AWS Management Console.
+ **Allow users to change their own password** – You can permit all IAM users in your account to change their own password. This gives users access to the `iam:ChangePassword` action for only their user and to the `iam:GetAccountPasswordPolicy` action. This option does not attach a permissions policy to each user. Rather, IAM applies the permissions at the account-level for all users. Alternatively, you can allow only some users to manage their own passwords. To do so, you clear this checkbox. For more information about using policies to limit who can manage passwords, see [Permit IAM users to change their own passwords](id_credentials_passwords_enable-user-change.md).
+ **Prevent password reuse** – You can prevent IAM users from reusing a specified number of previous passwords. You can specify a minimum number of 1 and a maximum number of 24 previous passwords that can't be repeated. 

## To set a password policy (console)


You can use the AWS Management Console to create, change, or delete a custom password policy. Changes to the password policy apply to new IAM users created after this policy change and existing IAM users when they change their passwords.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Account settings**.

1. In the **Password policy** section, choose **Edit**. 

1. Choose **Custom** to use a custom password policy.

1. Select the options that you want to apply to your password policy and choose **Save changes**. 

1. Confirm that you want to set a custom password policy by choosing **Set custom**.

The console displays a status message informing you that password requirements for IAM users have been updated..

------

## To change a password policy (console)


You can use the AWS Management Console to create, change, or delete a custom password policy. Changes to the password policy apply to new IAM users created after this policy change and existing IAM users when they change their passwords.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Account settings**.

1. In the **Password policy** section, choose **Edit**. 

1. Select the options that you want to apply to your password policy and choose **Save changes**. 

1. Confirm that you want to set a custom password policy by choosing **Set custom**.

The console displays a status message informing you that password requirements for IAM users have been updated.

------

## To delete a custom password policy (console)


You can use the AWS Management Console to create, change, or delete a custom password policy. Changes to the password policy apply to new IAM users created after this policy change and existing IAM users when they change their passwords.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Account settings**.

1. In the **Password policy** section, choose **Edit**. 

1. Choose **IAM default** to delete the custom password policy and choose **Save changes**.

1. Confirm that you want to set the IAM default password policy by choosing **Set default**.

The console displays a status message informing you that the password policy is set to IAM default.

------

## Setting a password policy (AWS CLI)


You can use the AWS Command Line Interface to set a password policy.

**To manage the custom account password policy from the AWS CLI**  
Run the following commands:
+ To create or change the custom password policy: [https://docs.aws.amazon.com/cli/latest/reference/iam/update-account-password-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-account-password-policy.html)
+ To view the password policy: [https://docs.aws.amazon.com/cli/latest/reference/iam/get-account-password-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-account-password-policy.html) 
+ To delete the custom password policy: [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-account-password-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-account-password-policy.html) 

## Setting a password policy (AWS API)


You can use AWS API operations to set a password policy.

**To manage the custom account password policy from the AWS API**  
Call the following operations:
+ To create or change the custom password policy: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccountPasswordPolicy.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccountPasswordPolicy.html)
+ To view the password policy: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountPasswordPolicy.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountPasswordPolicy.html) 
+ To delete the custom password policy: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccountPasswordPolicy.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccountPasswordPolicy.html) 

# Manage passwords for IAM users
Manage user passwords

IAM users who use the AWS Management Console to work with AWS resources must have a password in order to sign in. You can create, change, or delete a password for an IAM user in your AWS account. 

After you have assigned a password to a user, the user can sign in to the AWS Management Console using the sign-in URL for your account, which looks like this: 

```
https://12-digit-AWS-account-ID or alias.signin.aws.amazon.com/console
```

For more information about how IAM users sign in to the AWS Management Console, see [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*. 

Even if your users have their own passwords, they still need permissions to access your AWS resources. By default, a user has no permissions. To give your users the permissions they need, you assign policies to them or to the groups they belong to. For information about creating users and groups, see [IAM Identities](id.md). For information about using policies to set permissions, see [Change permissions for an IAM user](id_users_change-permissions.md). 

You can grant users permission to change their own passwords. For more information, see [Permit IAM users to change their own passwords](id_credentials_passwords_enable-user-change.md). For information about how users access your account sign-in page, see [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*. 

**Topics**
+ [

## Creating, changing, or deleting an IAM user password (console)
](#id_credentials_passwords_admin-change-user_console)

## Creating, changing, or deleting an IAM user password (console)


You can use the AWS Management Console to manage passwords for your IAM users.

The access needs of your users can change over time. You might need to enable a user intended for CLI access to have console access, change a user's password because they receive the email with their credentials, or delete a user when they leave your organization or no longer need AWS access. 

### To create an IAM user password (console)


Use this procedure to give a user console access by creating a password that is associated with the username.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. Choose the name of the user whose password you want to create. 

1. Choose the **Security credentials** tab, and then under **Console sign-in**, choose **Enable console access**.

1. In the **Enable console access** dialog box, select **Reset password**, then choose whether to have IAM generate a password or create a custom password: 
   + To have IAM generate a password, choose **Autogenerated password**.
   + To create a custom password, choose **Custom password**, and type the password. 
**Note**  
The password that you create must meet the account's [password policy](id_credentials_passwords_account-policy.md).

1. To require the user to create a new password when signing in, choose **Require password change at the next sign-in**. 

1. To require the user to use the new password immediately, select **Revoke active console sessions**. This attaches an inline policy to the IAM user that denies the user access to resources if their credentials are older than the time specified by the policy.

1. Choose **Reset password**

1. The **Console password** dialog informs you that you have enabled the user's new password. To view the password so you can share it with the user, choose **Show** in the **Console password** dialog box. Select **Download .csv file** to download a file with the user's credentials.
**Important**  
For security reasons, you cannot access the password after completing this step, but you can create a new password at any time.

The console displays a status message informing you that console access has been enabled.

------

### To change the password for an IAM user (console)


Use this procedure to update a password that is associated with the username.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. Choose the name of the user whose password you want to change. 

1. Choose the **Security credentials** tab, and then under **Console sign-in**, choose **Manage console access**.

1. In the **Manage console access** dialog box, select **Reset password**, then choose whether to have IAM generate a password or create a custom password: 
   + To have IAM generate a password, choose **Autogenerated password**.
   + To create a custom password, choose **Custom password**, and type the password. 
**Note**  
The password that you create must meet the account's [password policy](id_credentials_passwords_account-policy.md).

1. To require the user to create a new password when signing in, choose **Require password change at the next sign-in**. 

1. To require the user to use the new password immediately, select **Revoke active console sessions**. This attaches an inline policy to the IAM user that denies the user access to resources if their credentials are older than the time specified by the policy.

1. Choose **Reset password**

1. The **Console password** dialog informs you that you have enabled the user's new password. To view the password so you can share it with the user, choose **Show** in the **Console password** dialog box. Select **Download .csv file** to download a file with the user's credentials.
**Important**  
For security reasons, you cannot access the password after completing this step, but you can create a new password at any time.

The console displays a status message informing you that console access has been updated.

------

### To delete (disable) an IAM user password (console)


Use this procedure to delete a password that is associated with the username, removing console access for the user.

**Important**  
You can prevent an IAM user from accessing the AWS Management Console by removing their password. This prevents them from signing in to the AWS Management Console using their sign-in credentials. It does not change their permissions or prevent them from accessing the console using an assumed role. If the user has active access keys, they continue to function and allow access through the AWS CLI, Tools for Windows PowerShell, AWS API, or the AWS Console Mobile Application.

------
#### [ Console ]

1. Follow the sign-in procedure appropriate to your user type as described in the topic [How to sign in to AWS](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. On the **IAM Console Home** page, in the left navigation pane, enter your query in the **Search IAM** text box.

1. In the navigation pane, choose **Users**.

1. Choose the name of the user whose password you want to delete. 

1. Choose the **Security credentials** tab, and then under **Console sign-in**, choose **Manage console access**.

1. To require the user to stop using the console immediately, select **Revoke active console sessions**. This attaches an inline policy to the IAM user that denies the user access to resources if their credentials are older than the time specified by the policy.

1. Choose **Disable access**

The console displays a status message informing you that console access has been disabled.

------

### Creating, changing, or deleting an IAM user password (AWS CLI)


You can use the AWS CLI API to manage passwords for your IAM users.

**To create a password (AWS CLI)**

1. (Optional) To determine whether a user has a password, run this command: [aws iam get-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/get-login-profile.html)

1. To create a password, run this command: [aws iam create-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/create-login-profile.html)

**To change a user's password (AWS CLI)**

1. (Optional) To determine whether a user has a password, run this command: [aws iam get-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/get-login-profile.html)

1. To change a password, run this command: [aws iam update-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/update-login-profile.html)

**To delete (disable) a user's password (AWS CLI)**

1. (Optional) To determine whether a user has a password, run this command: [aws iam get-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/get-login-profile.html)

1. (Optional) To determine when a password was last used, run this command: [aws iam get-user](https://docs.aws.amazon.com/cli/latest/reference/iam/get-user.html)

1. To delete a password, run this command: [aws iam delete-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-login-profile.html)

**Important**  
When you delete a user's password, the user can no longer sign in to the AWS Management Console. If the user has active access keys, they continue to function and allow access through the AWS CLI, Tools for Windows PowerShell, or AWS API function calls. When you use the AWS CLI, Tools for Windows PowerShell, or AWS API to delete a user from your AWS account, you must first delete the password using this operation. For more information, see [Deleting an IAM user (AWS CLI)](id_users_remove.md#id_users_deleting_cli). 

**To revoke a user's active console sessions before a specified time (AWS CLI)**

1. To embed an inline policy that revokes an IAM user's active console sessions before a specified time, use the following inline policy and run this command: [aws iam put-user-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-user-policy.html)

   This inline policy denies all permissions and includes the `aws:TokenIssueTime` condition key. It revokes the user's active console sessions before the specified time in the `Condition` element of the inline policy. Replace the `aws:TokenIssueTime` condition key value with your own value.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": {
       "Effect": "Deny",
       "Action": "*",
       "Resource": "*",
       "Condition": {
         "DateLessThan": {
           "aws:TokenIssueTime": "2014-05-07T23:47:00Z"
         }
       }
     }
   }
   ```

------

1. (Optional) To list the names of the inline policies embedded in the IAM user, run this command: [aws iam list-user-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-user-policies.html)

1. (Optional) To view the named inline policy embedded in the IAM user, run this command: [aws iam get-user-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/get-user-policy.html)

### Creating, changing, or deleting an IAM user password (AWS API)


You can use the AWS API to manage passwords for your IAM users.

**To create a password (AWS API)**

1. (Optional) To determine whether a user has a password, call this operation: [GetLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html)

1. To create a password, call this operation: [CreateLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html)

**To change a user's password (AWS API)**

1. (Optional) To determine whether a user has a password, call this operation: [GetLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html)

1. To change a password, call this operation: [UpdateLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateLoginProfile.html)

**To delete (disable) a user's password (AWS API)**

1. (Optional) To determine whether a user has a password, run this command: [GetLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html)

1. (Optional) To determine when a password was last used, run this command: [GetUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html)

1. To delete a password, run this command: [DeleteLoginProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteLoginProfile.html)

**Important**  
When you delete a user's password, the user can no longer sign in to the AWS Management Console. If the user has active access keys, they continue to function and allow access through the AWS CLI, Tools for Windows PowerShell, or AWS API function calls. When you use the AWS CLI, Tools for Windows PowerShell, or AWS API to delete a user from your AWS account, you must first delete the password using this operation. For more information, see [Deleting an IAM user (AWS CLI)](id_users_remove.md#id_users_deleting_cli). 

**To revoke a user's active console sessions before a specified time (AWS API)**

1. To embed an inline policy that revokes an IAM user's active console sessions before a specified time, use the following inline policy and run this command: [PutUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPolicy.html)

   This inline policy denies all permissions and includes the `aws:TokenIssueTime` condition key. It revokes the user's active console sessions before the specified time in the `Condition` element of the inline policy. Replace the `aws:TokenIssueTime` condition key value with your own value.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": {
       "Effect": "Deny",
       "Action": "*",
       "Resource": "*",
       "Condition": {
         "DateLessThan": {
           "aws:TokenIssueTime": "2014-05-07T23:47:00Z"
         }
       }
     }
   }
   ```

------

1. (Optional) To list the names of the inline policies embedded in the IAM user, run this command: [ListUserPolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserPolicies.html)

1. (Optional) To view the named inline policy embedded in the IAM user, run this command: [GetUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUserPolicy.html)

# Permit IAM users to change their own passwords
Permit IAM users to change their own passwords

**Note**  
Users with federated identities will use the process defined by their identity provider to change their passwords. As a [best practice](best-practices.md), require human users to use federation with an identity provider to access AWS using temporary credentials.

You can grant IAM users the permission to change their own passwords for signing in to the AWS Management Console. You can do this in one of two ways:
+ [Allow all IAM users in the account to change their own passwords](#proc_letalluserschangepassword). 
+ [Allow only selected IAM users to change their own passwords](#proc_letselectuserschangepassword). In this scenario, you disable the option for all users to change their own passwords and you use an IAM policy to grant permissions to only some users. This approach allows those users to change their own passwords and optionally other credentials like their own access keys. 

**Important**  
We recommend that you [set a custom password policy](id_credentials_passwords_account-policy.md) that requires IAM users to create strong passwords.

## To allow all IAM users change their own passwords


------
#### [ Console ]

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, click **Account settings**.

1. In the **Password policy** section, choose **Edit**.

1. Choose **Custom** to use a custom password policy.

1. Select **Allow users to change their own password**, and then choose **Save changes**. This allows all users in the account access to the `iam:ChangePassword` action for only their user and to the `iam:GetAccountPasswordPolicy` action.

1. Provide users with the following instructions for changing their passwords: [How an IAM user changes their own password](id_credentials_passwords_user-change-own.md). 

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam update-account-password-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/update-account-password-policy.html)`

------
#### [ API ]

To create an alias for your AWS Management Console sign-in page URL, call the following operation:
+ `[UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccountPasswordPolicy.html)` 

------

## To allow selected IAM users change their own passwords


------
#### [ Console ]

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, click **Account settings**. 

1. In the **Password policy** section, make sure that **Allow users to change their own password** is not selected. If this checkbox is selected, all users can change their own passwords. (See the previous procedure.) 

1. Create the users who should be allowed to change their own password, if they do not already exist. For details, see [Create an IAM user in your AWS account](id_users_create.md). 

1. (Optional) Create an IAM group for the users who should be allowed to change their passwords, and then add the users from the previous step to the group. For details, see [IAM user groups](id_groups.md). 

1. Assign the following policy to the group. For more information, see [Manage IAM policies](access_policies_manage.md).

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": "iam:GetAccountPasswordPolicy",
         "Resource": "*"
       },
       {
         "Effect": "Allow",
         "Action": "iam:ChangePassword",
         "Resource": "arn:aws:iam::*:user/${aws:username}"
       }
     ]
   }
   ```

------

   This policy grants access to the [ChangePassword](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ChangePassword.html) action, which lets users change only their own passwords from the console, the AWS CLI, Tools for Windows PowerShell, or the API. It also grants access to the [GetAccountPasswordPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountPasswordPolicy.html) action, which lets the user view the current password policy; this permission is required so that the user can view the account password policy on the **Change password** page. The user must be allowed to read the current password policy to ensure that the changed password meets the requirements of the policy.

1. Provide users with the following instructions for changing their passwords: [How an IAM user changes their own password](id_credentials_passwords_user-change-own.md). 

------

### For more information


For more information on managing credentials, see the following topics:
+ [Permit IAM users to change their own passwords](#id_credentials_passwords_enable-user-change) 
+ [User passwords in AWS](id_credentials_passwords.md)
+ [Set an account password policy for IAM users](id_credentials_passwords_account-policy.md)
+ [Manage IAM policies](access_policies_manage.md)
+ [How an IAM user changes their own password](id_credentials_passwords_user-change-own.md)

# How an IAM user changes their own password


If you have been granted permission to change your own IAM user password, you can use a special page in the AWS Management Console to do this. You can also use the AWS CLI or AWS API.

**Topics**
+ [

## Permissions required
](#change-own-passwords-permissions-required)
+ [

## How IAM users change their own password (console)
](#ManagingUserPwdSelf-Console)
+ [

## How IAM users change their own password (AWS CLI or AWS API)
](#ManagingUserPwdSelf-CLIAPI)

## Permissions required


To change the password for your own IAM user, you must have the permissions from the following policy: [AWS: Allows IAM users to change their own console password on the Security credentials page](reference_policies_examples_aws_my-sec-creds-self-manage-password-only.md).

## How IAM users change their own password (console)


The following procedure describes how IAM users can use the AWS Management Console to change their own password.

**To change your own IAM user password (console)**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. On the **AWS IAM credentials** tab, choose **Update password**.

1. For **Current password**, enter your current password. Enter a new password for **New password** and **Confirm new password**. Then choose **Update password**.
**Note**  
The new password must meet the requirements of the account password policy. For more information, see [Set an account password policy for IAM users](id_credentials_passwords_account-policy.md). 

## How IAM users change their own password (AWS CLI or AWS API)


The following procedure describes how IAM users can use the AWS CLI or AWS API to change their own password.

**To change your own IAM password, use the following:**
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/change-password.html](https://docs.aws.amazon.com/cli/latest/reference/iam/change-password.html)
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ChangePassword.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ChangePassword.html)

# Manage access keys for IAM users
Manage access keys

**Important**  
As a [best practice](best-practices.md), use temporary security credentials (such as IAM roles) instead of creating long-term credentials like access keys. Before creating access keys, review the [alternatives to long-term access keys](security-creds-programmatic-access.md#security-creds-alternatives-to-long-term-access-keys).

Access keys are long-term credentials for an IAM user or the AWS account root user. You can use access keys to sign programmatic requests to the AWS CLI or AWS API (directly or using the AWS SDK). For more information, see [Programmatic access with AWS security credentials](security-creds-programmatic-access.md).

Access keys consist of two parts: an access key ID (for example, `AKIAIOSFODNN7EXAMPLE`) and a secret access key (for example, `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`). You must use both the access key ID and secret access key together to authenticate your requests.



When you create an access key pair, save the access key ID and secret access key in a secure location. The secret access key can be retrieved only at the time you create it. If you lose your secret access key, you must delete the access key and create a new one. For more instructions, see [Update access keys](id-credentials-access-keys-update.md).

You can have a maximum of two access keys per user.

**Important**  
IAM users with access keys are an account security risk. Manage your access keys securely. Do not provide your access keys to unauthorized parties, even to help [find your account identifiers](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html). By doing this, you might give someone permanent access to your account.  
When working with access keys, be aware of the following:  
**Do NOT** use your account's root credentials to create access keys.
**Do NOT** put access keys or credential information in your application files. 
**Do NOT** include files that contain access keys or credential information in your project area.
Access keys or credential information stored in the shared AWS credentials file are stored in plaintext.

## Monitoring recommendations


After creating access keys:
+ Use AWS CloudTrail to monitor access key usage and detect any unauthorized access attempts. For more information, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md).
+ Set up CloudWatch alarms to notify administrators for denied access attempts to help detect malicious activities. For more information, see the [Amazon CloudWatch User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/).
+ Regularly review, update, and delete access keys as needed.

The following topics detail management tasks associated with access keys.

**Topics**
+ [

## Monitoring recommendations
](#monitor-access-keys)
+ [

# Control the use of access keys by attaching an inline policy to an IAM user
](access-keys_inline-policy.md)
+ [

# Permissions required to manage access keys
](access-keys_required-permissions.md)
+ [

# How IAM users can manage their own access keys
](access-key-self-managed.md)
+ [

# How an IAM administrator can manage IAM user access keys
](access-keys-admin-managed.md)
+ [

# Update access keys
](id-credentials-access-keys-update.md)
+ [

# Secure access keys
](securing_access-keys.md)

# Control the use of access keys by attaching an inline policy to an IAM user
Control the use of access keys

As a best practice we recommend that [workloads use temporary credentials with IAM roles](best-practices.md#bp-workloads-use-roles) to access AWS. IAM users with access keys should be assigned least privilege access and have [multi-factor authentication (MFA)](id_credentials_mfa.md) enabled. For more information about assuming IAM roles, see [Methods to assume a role](id_roles_manage-assume.md).

However, if you're creating a proof of concept test of a service automation or other short-term use case, and you choose to run workloads using an IAM user with access keys we recommend that you [use policies conditions to further restrict access](best-practices.md#use-policy-conditions) of their IAM user credentials.

In this situation you can either create a time-bound policy that expires the credentials after the specified time or, if you are running a workload from a secure network, you can use an IP restriction policy.

For both these use cases, you can use an inline policy that's attached to the IAM user that has access keys.

**To configure a time-bound policy for an IAM user**

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, choose **Users** and then select the user for the short-term use case. If you haven't created the user yet, you can [create the user](getting-started-workloads.md) now.

1. On the user **Details** page, choose the **Permissions** tab.

1. Choose **Add permissions** and then select **Create inline policy**.

1. In the **Policy editor** section, select **JSON** to display the JSON editor.

1. In the JSON editor, enter the following policy, replacing the value for the `aws:CurrentTime` timestamp with your desired expiration date and time:

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

****  

   ```
   {
   "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
         "DateGreaterThan": {
         "aws:CurrentTime": "2025-03-01T00:12:00Z"
           }
         }
       }
     ]
   }
   ```

------

   This policy uses the `Deny` effect to restrict all actions on all resources after the specified date. The `DateGreaterThan` condition compares the current time with the timestamp you set.

1. Select **Next** to proceed to the **Review and create** page. In **Policy** details, under **Policy name** enter a name for the policy and then choose **Create policy**.

After the policy is created, it's displayed on the **Permissions** tab for the user. When the current time is greater than or equal to the time specified in the policy, the user will no longer have access to AWS resources. Make sure to inform workload developers of the expiration date you specified for these access keys. 

**To configure an IP restriction policy for an IAM user**

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, choose **Users** and then select the user that will run the workload from the secure network. If you haven't created the user yet, you can [create the user](getting-started-workloads.md) now.

1. On the user **Details** page, choose the **Permissions** tab.

1. Choose **Add permissions** and then select **Create inline policy**.

1. In the **Policy editor** section, select **JSON** to display the JSON editor.

1. Copy the following IAM policy into the JSON editor, and change the public IPv4 or IPv6 addresses, or ranges to your needs. You can use [https://checkip.amazonaws.com/](https://checkip.amazonaws.com/) to determine your current public IP address. You can specify individual IP addresses, or ranges of IP addresses using slash notation. For more information, see [aws:SourceIp](reference_policies_condition-keys.md#condition-keys-sourceip). 
**Note**  
The IP addresses must not be obfuscated by a VPN or a proxy server.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid":"IpRestrictionIAMPolicyForIAMUser",
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
           "NotIpAddress": {
             "aws:SourceIp": [
               "203.0.113.0/24",
               "2001:DB8:1234:5678::/64",
               "203.0.114.1"
             ]
           },
           "BoolIfExists": {
             "aws:ViaAWSService": "false"
           }
         }
       }
     ]
   }
   ```

------

   This policy example denies the use of an IAM user’s access keys with this policy applied, unless the request originated from the networks (specified in CIDR notation) “203.0.113.0/24”, “2001:DB8:1234:5678::/64”, or the specific IP address “203.0.114.1” 

1. Select **Next** to proceed to the **Review and create** page. In **Policy** details, under **Policy name** enter a name for the policy and then choose **Create policy**.

After the policy is created, it's displayed on the **Permissions** tab for the user. 

You could also apply this policy as a service control policy (SCP) across multiple AWS accounts in AWS Organizations, we recommend using an additional condition, `aws:PrincipalArn` to make this policy statement only apply to IAM users within the AWS accounts subject to this SCP. The following policy is includes that update:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "IpRestrictionServiceControlPolicyForIAMUsers",
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "NotIpAddress": {
          "aws:SourceIp": [
            "203.0.113.0/24",
            "2001:DB8:1234:5678::/64",
            "203.0.114.1"
          ]
        },
        "BoolIfExists": {
          "aws:ViaAWSService": "false"
        },
        "ArnLike": {
          "aws:PrincipalArn": "arn:aws:iam::*:user/*"
        }
      }
    }
  ]
}
```

------

# Permissions required to manage access keys


**Note**  
`iam:TagUser` is an optional permission for adding and editing descriptions for the access key. For more information, see [Tag IAM users](id_tags_users.md)

To create access keys for your own IAM user, you must have the permissions from the following policy:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "CreateOwnAccessKeys",
            "Effect": "Allow",
            "Action": [
                "iam:CreateAccessKey",
                "iam:GetUser",
                "iam:ListAccessKeys",
                "iam:TagUser"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        }
    ]
}
```

------

To update access keys for your own IAM user, you must have the permissions from the following policy:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ManageOwnAccessKeys",
            "Effect": "Allow",
            "Action": [
                "iam:CreateAccessKey",
                "iam:DeleteAccessKey",
                "iam:GetAccessKeyLastUsed",
                "iam:GetUser",
                "iam:ListAccessKeys",
                "iam:UpdateAccessKey",
                "iam:TagUser"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        }
    ]
}
```

------

# How IAM users can manage their own access keys


IAM administrators can grant IAM users the permission to self-manage their access keys by attaching the policy described in [Permissions required to manage access keys](access-keys_required-permissions.md).

With these permissions, IAM user can use the following procedures to create, activate, deactivate, and delete the access keys associated with their username.

**Topics**
+ [

## Create an access key for yourself (console)
](#Using_CreateAccessKey)
+ [

## Deactivate your access key (console)
](#deactivate-access-key-seccreds)
+ [

## Activate your access key (console)
](#activate-access-key-seccreds)
+ [

## Delete your access key (console)
](#delete-access-key-seccreds)

## Create an access key for yourself (console)


If you have been granted the appropriate permissions you can use the AWS Management Console to create access keys for yourself.

**To create your own access keys (console)**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. In the **Access keys** section, choose **Create access key**. If you already have two access keys, this button is deactivated and you must delete an access key before you can create a new one.

1. On the **Access key best practices & alternatives** page, choose your use case to learn about additional options which can help you avoid creating a long-term access key. If you determine that your use case still requires an access key, choose **Other** and then choose **Next**.

1. (Optional) Set a description tag value for the access key. This adds a tag key-value pair to your IAM user. This can help you identify and update access keys later. The tag key is set to the access key id. The tag value is set to the access key description that you specify. When you are finished, choose **Create access key**.

1. On the **Retrieve access keys** page, choose either **Show** to reveal the value of your user's secret access key, or **Download .csv file**. This is your only opportunity to save your secret access key. After you've saved your secret access key in a secure location, choose **Done**.

## Deactivate your access key (console)


If you have been granted the appropriate permissions you can use the AWS Management Console to deactivate your access key.

**To deactivate an access key**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. In the **Access keys** section find the key you want to deactivate, then choose **Actions**, then choose **Deactivate**. When prompted for confirmation, choose **Deactivate**. A deactivated access key still counts toward your limit of two access keys.

## Activate your access key (console)


If you have been granted the appropriate permissions you can use the AWS Management Console to activate your access key.

**To activate an access key**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. In the **Access keys** section, find the key to activate, then choose **Actions**, then choose **Activate**.

## Delete your access key (console)


If you have been granted the appropriate permissions you can use the AWS Management Console to delete your access key.

**To delete an access key when you no longer need it**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. In the **Access keys** section, find the key you want to delete, then choose **Actions**, then choose **Delete**. Follow the instructions in the dialog to first **Deactivate** and then confirm the deletion. We recommend that you verify that the access key is no longer in use before you permanently delete it.

# How an IAM administrator can manage IAM user access keys


IAM administrators can create, activate, deactivate, and delete the access keys associated with individual IAM users. They can also list the IAM users in the account which have access keys and locate which IAM user has a specific access key.

**Topics**
+ [

## To create an access key for an IAM user
](#admin-create-access-key)
+ [

## To deactivate an access key for an IAM user
](#admin-deactivate-access-key)
+ [

## To activate an access key for an IAM user
](#admin-activate-access-key)
+ [

## To delete an access key for an IAM user
](#admin-delete-access-key)
+ [

## To list the access keys for an IAM user
](#admin-list-access-key)
+ [

## To list the access keys for an IAM user
](#admin-list-access-key)
+ [

## To display all the access key IDs for users in your account
](#admin-list-all-access-keys)
+ [

## To use an access key ID to find a user
](#admin-find-user-access-keys)
+ [

## To find the most recent use of an access key ID
](#admin-find-most-recent-use-access-keys)

## To create an access key for an IAM user


------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, in the **Access keys** section, choose **Create access key**.

   If the button is deactivated, then you must delete one of the existing keys before you can create a new one.

1. On the **Access key best practices & alternatives** page, review the best practices and alternatives. Choose your use case to learn about additional options which can help you avoid creating a long-term access key.

1. If you determine that your use case still requires an access key, choose **Other** and then choose **Next**.

1. **(Optional)** On the **Set description tag** page, you can add a description tag to the access key to help track your access key. Select **Create access key**.

1. On the **Retrieve access key page**, choose **Show** to reveal the value of your user's secret access key.

1. To save the access key ID and secret access key to a `.csv` file to a secure location on your computer, choose the **Download .csv file** button.
**Important**  
This is your only time to view or download the newly created access key and you cannot recover it. Make sure you securely maintain your access key.

When you create an access key for your user, that key pair is active by default, and your user can use the pair right away.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html) 

------

## To deactivate an access key for an IAM user


------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, in the **Access keys** section, choose the **Actions** drop-down menu, then choose **Deactivate**.

1. In the **Deactivate** dialog box, confirm that you want to deactivate the access key by selecting **Deactivate**

After an access key is deactivated, it can no longer be used by API calls. You can activate it again if needed.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html) 

------

## To activate an access key for an IAM user


------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, in the **Access keys** section, choose the **Actions** drop-down menu, then choose **Activate**.

After an access key is activated, it can be used by API calls. You can deactivate it again if needed.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html) 

------

## To delete an access key for an IAM user


After an access key has been deactivated, if it is no longer required, delete it.

------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, in the **Access keys** section, choose the **Actions** drop-down menu for the inactive access key, then choose **Delete**.

1. In the **Delete** dialog box, confirm that you want to delete the access key by entering the access key ID in the text input field and then selecting **Delete**.

After an access key is deleted, it can't be recovered.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html) 

------

## To list the access keys for an IAM user


You can view a list of the access key IDs associated with an IAM user. 

------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, the the **Access keys** section lists the access keys for the user.

Each IAM user can have two access keys.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html) 

------

## To list the access keys for an IAM user


You can view a list of the access key IDs associated with an IAM user. 

------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. On **Security credentials** tab, the **Access keys** section lists the access key IDs for the user including the status of each key displayed.
**Note**  
Only the user's access key ID is visible. The secret access key can only be retrieved when the key is created.

Each IAM user can have two access keys.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html) 

------

## To display all the access key IDs for users in your account


You can view a list of the access key IDs for users in your AWS account. 

------
#### [ Console ]

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, choose **Users**.

1. Choose the user name to go to the user details page.

1. If necessary, add the **Access key ID** column to the users table by completing the following steps:

   1. Above the table on the far right, choose the **Preferences** icon (![\[Preferences icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)).

   1. In the **Preferences** dialog box, under **Select visible columns** turn on **Access key ID**.

   1. Choose **Confirm** to return to the list of users. The list is updated to include the access key ID.

1. The **Access key ID** column shows the state of each access key, followed by its ID; for example, **`Active - AKIAIOSFODNN7EXAMPLE`** or **`Inactive - AKIAI44QH8DHBEXAMPLE`**. 

   You can use this information to view and copy the access keys IDs for users with one or two access keys. The column displays **`-`** for users with no access key.
**Note**  
The secret access key can only be retrieved when the key is created.

Each IAM user can have two access keys.

------

## To use an access key ID to find a user


You can use an access key ID to find a user in your AWS account. 

------
#### [ Console ]

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, in the search box, enter the **Access key ID**, for example AKIAI44QH8DHBEXAMPLE. 

1. The IAM user that the access key ID is associated with appears in the navigation pane. Choose the user name to go to the user details page.

------

## To find the most recent use of an access key ID


The most recent use of an access key is displayed in the user's list on the IAM users page, on the user detail page, and is part of the credential report. 

------
#### [ Console ]

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 users list, see the **Access key last used** column.

   If the column is not displayed, choose the **Preferences** icon (![\[Preferences icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)) and under **Select visible columns** turn on **Access key last used** to display the column.

1. (optional) In the navigation pane, under **Access reports**, select **Credential report** to download a report that includes the access key last used information for all of the IAM users in your account.

1. (optional) Select the IAM user to view the user details. The **Summary** section includes the access key IDs, their status, and when they were last used.

------
#### [ AWS CLI ]

Run the following command:
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html)

------
#### [ API ]

Call the following operation:
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html) 

------

# Update access keys


As a security [best practice](best-practices.md#update-access-keys), we recommend that you update IAM user access keys when needed, such as when an employee leaves your company. IAM users can update their own access keys if they have been granted the necessary permissions.

For details about granting IAM users permissions to update their own access keys, see [AWS: Allows IAM users to manage their own password, access keys, and SSH public keys on the Security credentials page](reference_policies_examples_aws_my-sec-creds-self-manage-pass-accesskeys-ssh.md). You can also apply a password policy to your account to require that all of your IAM users periodically update their passwords and how often they must do so. For more information, see [Set an account password policy for IAM users](id_credentials_passwords_account-policy.md). 

**Note**  
If you lose your secret access key, you must delete the access key and create a new one. The secret access key can be retrieved only at the time you create it. Use this procedure to deactivate and then replace any lost access keys with new credentials.

**Topics**
+ [

## Updating IAM user access keys (console)
](#rotating_access_keys_console)
+ [

## Updating access keys (AWS CLI)
](#rotating_access_keys_cli)
+ [

## Updating access keys (AWS API)
](#rotating_access_keys_api)

## Updating IAM user access keys (console)


You can update access keys from the AWS Management Console.

**To update access keys for an IAM user without interrupting your applications (console)**

1. While the first access key is still active, create a second access key.

   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, choose **Users**.

   1. Choose the name of the intended user, and then choose the **Security credentials** tab.

   1. In the **Access keys** section, choose **Create access key**. On the **Access key best practices & alternatives** page, choose **Other**, then choose **Next**.

   1. (Optional) Set a description tag value for the access key to add a tag key-value pair to this IAM user. This can help you identify and update access keys later. The tag key is set to the access key id. The tag value is set to the access key description that you specify. When you are finished, choose **Create access key**.

   1. On the **Retrieve access keys** page, choose either **Show** to reveal the value of your user's secret access key, or **Download .csv file**. This is your only opportunity to save your secret access key. After you've saved your secret access key in a secure location, choose **Done**.

      When you create an access key for your user, that key pair is active by default, and your user can use the pair right away. At this point, the user has two active access keys.

1. Update all applications and tools to use the new access key.

1. <a name="id_credentials_access-keys-key-still-in-use"></a>Determine whether the first access key is still in use by reviewing the **Last used** information for the oldest access key. One approach is to wait several days and then check the old access key for any use before proceeding.

1. Even if the **Last used** information indicates that the old key has never been used, we recommend that you do not immediately delete the first access key. Instead, choose **Actions** and then choose **Deactivate** to deactivate the first access key.

1. Use only the new access key to confirm that your applications are working. Any applications and tools that still use the original access key will stop working at this point because they no longer have access to AWS resources. If you find such an application or tool, you can reactivate the first access key. Then return to [Step 3](#id_credentials_access-keys-key-still-in-use) and update this application to use the new key.

1. After you wait some period of time to ensure that all applications and tools have been updated, you can delete the first access key:

   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, choose **Users**.

   1. Choose the name of the intended user, and then choose the **Security credentials** tab.

   1. In the **Access keys** section for the access key you want to delete, choose **Actions**, and then choose **Delete**. Follow the instructions in the dialog to first **Deactivate** and then confirm the deletion.

**To determine which access keys need to be updated or deleted (console)**

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, choose **Users**.

1. If necessary, add the **Access key age** column to the users table by completing the following steps:

   1. Above the table on the far right, choose the settings icon (![\[Settings icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)).

   1. In **Manage columns**, select **Access key age**.

   1. Choose **Close** to return to the list of users.

1. The **Access key age** column shows the number of days since the oldest active access key was created. You can use this information to find users with access keys that might need to be updated or deleted. The column displays **None** for users with no access key.

## Updating access keys (AWS CLI)


You can update access keys from the AWS Command Line Interface.

**To update access keys without interrupting your applications (AWS CLI)**

1. While the first access key is still active, create a second access key, which is active by default. Run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html)

     At this point, the user has two active access keys.

1. <a name="step-update-apps"></a>Update all applications and tools to use the new access key.

1. <a name="step-determine-use"></a>Determine whether the first access key is still in use by using this command:
   +  [https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html)

   One approach is to wait several days and then check the old access key for any use before proceeding.

1. Even if step [Step 3](#step-determine-use) indicates no use of the old key, we recommend that you do not immediately delete the first access key. Instead, change the state of the first access key to `Inactive` using this command:
   +  [https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-access-key.html)

1. Use only the new access key to confirm that your applications are working. Any applications and tools that still use the original access key will stop working at this point because they no longer have access to AWS resources. If you find such an application or tool, you can switch its state back to `Active` to reactivate the first access key. Then return to step [Step 2](#step-update-apps) and update this application to use the new key.

1. After you wait some period of time to ensure that all applications and tools have been updated, you can delete the first access key with this command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html)

## Updating access keys (AWS API)


You can update access keys using the AWS API.

**To update access keys without interrupting your applications (AWS API)**

1. While the first access key is still active, create a second access key, which is active by default. Call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html)

     At this point, the user has two active access keys.

1. <a name="step-update-apps-2"></a>Update all applications and tools to use the new access key.

1. <a name="step-determine-use-2"></a>Determine whether the first access key is still in use by calling this operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html)

   One approach is to wait several days and then check the old access key for any use before proceeding.

1. Even if step [Step 3](#step-determine-use-2) indicates no use of the old key, we recommend that you do not immediately delete the first access key. Instead, change the state of the first access key to `Inactive` calling this operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html)

1. Use only the new access key to confirm that your applications are working. Any applications and tools that still use the original access key will stop working at this point because they no longer have access to AWS resources. If you find such an application or tool, you can switch its state back to `Active` to reactivate the first access key. Then return to step [Step 2](#step-update-apps-2) and update this application to use the new key.

1. After you wait some period of time to ensure that all applications and tools have been updated, you can delete the first access key calling this operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html)

# Secure access keys


Anyone who has your access keys has the same level of access to your AWS resources that you do. Consequently, AWS goes to significant lengths to protect your access keys, and, in keeping with our [shared-responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/), you should as well. 

Expand the following sections for guidance to help you protect your access keys. 

**Note**  
Your organization may have different security requirements and policies than those described in this topic. The suggestions provided here are intended as general guidelines. 

## Remove (or don't generate) AWS account root user access keys


**One of the best ways to protect your account is to not have access keys for your AWS account root user.** Unless you must have root user access keys (which is rare), it is best not to generate them. Instead, create an administrative user in AWS IAM Identity Center for daily administrative tasks.For information about how to create an administrative user in IAM Identity Center, see [Getting started](https://docs.aws.amazon.com//singlesignon/latest/userguide/getting-started.html) in the *IAM Identity Center User Guide*.

If you already have root user access keys for your account, we recommend the following: Find places in your applications where you are currently using access keys (if any), and replace the root user access keys with IAM user access keys. Then disable and remove the root user access keys. For more information about how to update access keys, see [Update access keys](id-credentials-access-keys-update.md)



## Use temporary security credentials (IAM roles) instead of long-term access keys


In many scenarios, you don't need long-term access keys that never expire (as you have with an IAM user). Instead, you can create IAM roles and generate temporary security credentials. Temporary security credentials consist of an access key ID and a secret access key, but they also include a security token that indicates when the credentials expire. 

Long-term access keys, such as those associated with IAM users and the root user, remain valid until you manually revoke them. However, temporary security credentials obtained through IAM roles and other features of the AWS Security Token Service expire after a short period of time. Use temporary security credentials to help reduce your risk in case credentials are accidentally exposed.

Use an IAM role and temporary security credentials in these scenarios:
+ **You have an application or AWS CLI scripts running on an Amazon EC2 instance.** Don't use access keys directly in your application. Don't pass access keys to the application, embed them in the application, or let the application read access keys from any source. Instead, define an IAM role that has appropriate permissions for your application and launch the Amazon Elastic Compute Cloud (Amazon EC2) instance with [roles for EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html). Doing this associates an IAM role with the Amazon EC2 instance. This practice also enables the application to get temporary security credentials that it can in turn use to make programmatic calls to AWS. The AWS SDKs and the AWS Command Line Interface (AWS CLI) can get temporary credentials from the role automatically. 
+ **You need to grant cross-account access.** Use an IAM role to establish trust between accounts, and then grant users in one account limited permissions to access the trusted account. For more information, see [IAM tutorial: Delegate access across AWS accounts using IAM roles](tutorial_cross-account-with-roles.md).
+ **You have a mobile app.** Don't embed access keys with the app, even in encrypted storage. Instead, use [Amazon Cognito](https://aws.amazon.com/cognito/) to manage user identities in your app. This service lets you authenticate users using Login with Amazon, Facebook, Google, or any OpenID Connect (OIDC)–compatible identity provider. You can then use the Amazon Cognito credentials provider to manage credentials that your app uses to make requests to AWS.
+ **You want to federate into AWS and your organization supports SAML 2.0.** If you work for an organization that has an identity provider that supports SAML 2.0, configure the provider to use SAML. You can use SAML to exchange authentication information with AWS and get back a set of temporary security credentials. For more information, see [SAML 2.0 federation](id_roles_providers_saml.md).
+ **You want to federate into AWS and your organization has an on-premises identity store.** If users can authenticate inside your organization, you can write an application that can issue them temporary security credentials for access to AWS resources. For more information, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).
+ **Use conditions in IAM policies to only allow access from expected networks.** You can limit where and how your access keys are used by implementing [IAM policies with conditions](reference_policies_elements_condition_operators.md) that specify and allow only expected networks, such as your public IP addresses or Virtual Private Clouds (VPCs). This way you know access keys can only be used from expected and acceptable networks. 

**Note**  
Are you using an Amazon EC2 instance with an application that requires programmatic access to AWS resources? If so, use [IAM roles for EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html).

## Manage IAM user access keys properly


If you must create access keys for programmatic access to AWS, create them for IAM users, granting the users only the permissions they require.

Observe these precautions to help protect IAM user access keys:
+ **Don't embed access keys directly into code.** The [AWS SDKs](https://aws.amazon.com/tools/#sdk) and the [AWS Command Line Tools](https://aws.amazon.com/tools/#cli) enable you to put access keys in known locations so that you don't have to keep them in code. 

  Put access keys in one of the following locations:
  + **The AWS credentials file.** The AWS SDKs and AWS CLI automatically use the credentials that you store in the AWS credentials file. 

    For information about using the AWS credentials file, see the documentation for your SDK. Examples include [Set AWS Credentials and Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-credentials.html) in the *AWS SDK for Java Developer Guide* and [Configuration and credential files](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) in the *AWS Command Line Interface User Guide*.

    To store credentials for the AWS SDK for .NET and the AWS Tools for Windows PowerShell, we recommend that you use the SDK Store. For more information, see [Using the SDK Store](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/sdk-store.html) in the *AWS SDK for .NET Developer Guide*.
  + **Environment variables.** On a multi-tenant system, choose user environment variables, not system environment variables. 

    For more information about using environment variables to store credentials, see [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html) in the *AWS Command Line Interface User Guide*. 
+ **Use different access keys for different applications.** Do this so that you can isolate the permissions and revoke the access keys for individual applications if they are exposed. Having separate access keys for different applications also generates distinct entries in [AWS CloudTrail](https://aws.amazon.com/cloudtrail/) log files. This configuration makes it easier for you to determine which application performed specific actions. 
+ **Update access keys when needed.** If there is a risk that the access key could be compromised, update the access key and delete the previous access key. For details, see [Update access keys](id-credentials-access-keys-update.md) 
+ **Remove unused access keys.** If a user leaves your organization, remove the corresponding IAM user so that the user can no longer access your resources. To find out when an access key was last used, use the [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html) API (AWS CLI command: [https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html)).
+ **Use temporary credentials and configure multi-factor authentication for your most sensitive API operations.** With IAM policies, you can specify which API operations a user is allowed to call. In some cases, you might want the additional security of requiring users to be authenticated with AWS MFA before you allow them to perform particularly sensitive actions. For example, you might have a policy that allows a user to perform the Amazon EC2 `RunInstances`, `DescribeInstances`, and `StopInstances` actions. But you might want to restrict a destructive action like `TerminateInstances` and ensure that users can perform that action only if they authenticate with an AWS MFA device. For more information, see [Secure API access with MFA](id_credentials_mfa_configure-api-require.md).

## Access the mobile app using AWS access keys


You can access a limited set of AWS services and features using the AWS mobile app. The mobile app helps you support incident response while on the go. For more information and to download the app, see [AWS Console Mobile Application](https://aws.amazon.com/console/mobile/).

You can sign in to the mobile app using your console password or your access keys. As a best practice, do not use root user access keys. Instead, we strongly recommend that in addition to using a password or biometric lock on your mobile device, you create an IAM user specifically for managing AWS resources using the mobile app. If you lose your mobile device, you can remove the IAM user's access.

**To sign in using access keys (mobile app)**

1. Open the app on your mobile device.

1. If this is the first time that you're adding an identity to the device, choose **Add an identity** and then choose **Access keys**.

   If you have already signed in using another identity, choose the menu icon and choose **Switch identity**. Then choose **Sign in as a different identity** and then **Access keys**.

1. On the **Access keys** page, enter your information:
   + **Access key ID** – Enter your access key ID.
   + **Secret access key** – Enter your secret access key.
   + **Identity name** – Enter the name of the identity that will appear in the mobile app. This does not need to match your IAM user name.
   + **Identity PIN** – Create a personal identification number (PIN) that you will use for future sign-ins.
**Note**  
If you enable biometrics for the AWS mobile app, you will be prompted to use your fingerprint or facial recognition for verification instead of the PIN. If the biometrics fail, you might be prompted for the PIN instead.

1. Choose **Verify and add keys**.

   You can now access a select set of your resources using the mobile app.

## Related information


The following topics provide guidance for setting up the AWS SDKs and the AWS CLI to use access keys:
+ [Set AWS credentials and Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-credentials.html) in the *AWS SDK for Java Developer Guide*
+ [Using the SDK Store](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/sdk-store.html) in the *AWS SDK for .NET Developer Guide*
+ [Providing Credentials to the SDK](https://docs.aws.amazon.com/aws-sdk-php/v2/guide/credentials.html) in the *AWS SDK for PHP Developer Guide*
+ [Configuration](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration) in the Boto 3 (AWS SDK for Python) documentation
+ [Using AWS Credentials](https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html) in the *AWS Tools for Windows PowerShell User Guide* 
+ [Configuration and credential files](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) in the *AWS Command Line Interface User Guide* 
+ [Granting access using an IAM role](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html) in the *AWS SDK for .NET Developer Guide*
+ [Configure IAM roles for Amazon EC2](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java-dg-roles.html) in the *AWS SDK for Java 2.x*

## Using access keys and secret key credentials for console access


It is possible to use access key and secret key credentials for direct AWS Management Console access, not just the AWS CLI. This can be achieved using the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API call. By constructing a console URL using the temporary credentials and token provided by `GetFederationToken`, IAM principals can access the console. For more information, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).

It is worth clarifying that when signing into the console directly using IAM or root user credentials with MFA enabled, MFA will be required. However, if the method described above (using temporary credentials with `GetFederationToken`) is used, MFA will NOT be required.



## Auditing access keys


You can review the AWS access keys in your code to determine whether the keys are from an account that you own. You can pass an access key ID using the [https://docs.aws.amazon.com/cli/latest/reference/sts/get-access-key-info.html](https://docs.aws.amazon.com/cli/latest/reference/sts/get-access-key-info.html) AWS CLI command or the [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetAccessKeyInfo.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetAccessKeyInfo.html) AWS API operation.

The AWS CLI and AWS API operations return the ID of the AWS account to which the access key belongs. Access key IDs beginning with `AKIA` are long-term credentials for an IAM user or an AWS account root user. Access key IDs beginning with `ASIA` are temporary credentials that are created using AWS STS operations. If the account in the response belongs to you, you can sign in as the root user and review your root user access keys. Then, you can pull a [credentials report](id_credentials_getting-report.md) to learn which IAM user owns the keys. To learn who requested the temporary credentials for an `ASIA` access key, view the AWS STS events in your CloudTrail logs.

For security purposes, you can [review AWS CloudTrail logs](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds) to learn who performed an action in AWS. You can use the `sts:SourceIdentity` condition key in the role trust policy to require users to specify an identity when they assume a role. For example, you can require that IAM users specify their own user name as their source identity. This can help you determine which user performed a specific action in AWS. For more information, see [`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity).

This operation does not indicate the state of the access key. The key might be active, inactive, or deleted. Active keys might not have permissions to perform an operation. Providing a deleted access key might return an error that the key doesn't exist.

# AWS Multi-factor authentication in IAM
Multi-factor authentication

For increased security, we recommend that you configure multi-factor authentication (MFA) to help protect your AWS resources. You can enable MFA for the AWS account root user of all AWS accounts, including standalone accounts, management accounts, and member accounts, as well as for your IAM users. We recommend that you use phishing-resistant MFA such as passkeys and security keys whenever possible. These FIDO-based authenticators use public key cryptography and are resistant to phishing, man-in-the-middle, and replay attacks, providing a stronger level of security than TOTP-based options.

MFA is enforced for all account types for their root user. For more information, see [Secure your AWS Organizations account root user credentials](root-user-best-practices.md#ru-bp-organizations). 

When you enable MFA for the root user, it affects only the root user credentials. IAM users in the account are distinct identities with their own credentials, and each identity has its own MFA configuration. For more information about using MFA to protect the root user, see [Multi-factor authentication for AWS account root user](enable-mfa-for-root.md).

Your AWS account root user and IAM users can register up to eight MFA devices of any type. Registering multiple MFA devices can provide flexibility and help you reduce the risk of access interruption if a device is lost or broken. You only need one MFA device to sign in to the AWS Management Console or create a session through the AWS CLI.

**Note**  
We recommend that you require your human users to use temporary credentials when accessing AWS. Have you considered using AWS IAM Identity Center? You can use IAM Identity Center to centrally manage access to multiple AWS accounts and provide users with MFA-protected, single sign-on access to all their assigned accounts from one place. With IAM Identity Center, you can create and manage user identities in IAM Identity Center or easily connect to your existing SAML 2.0 compatible identity provider. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the *AWS IAM Identity Center User Guide*.

MFA adds extra security that requires users to provide unique authentication from an AWS supported MFA mechanism in addition to their sign-in credentials when they access AWS websites or services.

## MFA types


AWS supports the following MFA types:

**Contents**
+ [

### Passkeys and security keys
](#passkeys-security-keys-for-iam-users)
+ [

### Virtual authenticator applications
](#virtual-auth-apps-for-iam-users)
+ [

### Hardware TOTP tokens
](#hardware-totp-token-for-iam-users)

### Passkeys and security keys


AWS Identity and Access Management supports passkeys and security keys for MFA. Based on FIDO standards, passkeys use public key cryptography to provide strong, phishing-resistant authentication that is more secure than passwords. AWS supports two types of passkeys: device-bound passkeys (security keys) and synced passkeys.
+ **Security keys**: These are physical devices, like a YubiKey, used as a second factor for authentication. A single security key can support multiple root user accounts and IAM users.
+ **Synced passkeys**: These use credential managers from providers such as Google, Apple, Microsoft accounts, and third-party services like 1Password, Dashlane, and Bitwarden as a second factor.

You can use built-in biometric authenticators, like Touch ID on Apple MacBooks, to unlock your credential manager and sign in to AWS. Passkeys are created with your chosen provider using your fingerprint, face, or device PIN. You can also use a cross-device authentication (CDA) passkey from one device, like a mobile device or hardware security key, to sign in on another device like a laptop. For more information, see [cross-device authentication](https://passkeys.dev/docs/reference/terms/#cross-device-authentication-cda) (CDA).

You can sync passkeys across your devices to facilitate sign-ins with AWS, enhancing usability and recoverability. For more information about enabling passkeys and security keys, see [Enable a passkey or security key for the root user (console)](enable-fido-mfa-for-root.md).

The FIDO Alliance maintains a list of all [FIDO Certified products](https://fidoalliance.org/certification/fido-certified-products/) that are compatible with FIDO specifications.

### Virtual authenticator applications


A virtual authenticator application runs on a phone or other device and emulates a physical device. Virtual authenticator apps implement the [time-based one-time password (TOTP) algorithm](https://datatracker.ietf.org/doc/html/rfc6238) and support multiple tokens on a single device. The user must type a valid code from the device when prompted during sign-in. Each token assigned to a user must be unique. A user can't type a code from another user's token to authenticate.

We recommend that you use phishing-resistant MFA such as [passkeys or security keys](#passkeys-security-keys-for-iam-users) for the strongest protection. If you are not yet able to use passkeys or security keys, we recommend that you use a virtual MFA device as an interim measure while waiting for hardware purchase approval or while you wait for your hardware to arrive. For a list of a few supported apps that you can use as virtual MFA devices, see [Multi-Factor Authentication (MFA)](https://aws.amazon.com/iam/features/mfa/?audit=2019q1).

For instructions on setting up a virtual MFA device for an IAM user, see [Assign a virtual MFA device in the AWS Management Console](id_credentials_mfa_enable_virtual.md).

**Note**  
Unassigned virtual MFA devices in your AWS account are deleted when you’re adding new virtual MFA devices either via the AWS Management Console or during the sign-in process. Unassigned virtual MFA devices are devices in your account but not used by account root user or IAM users for the sign-in process. They’re deleted so new virtual MFA devices can be added to your account. It also allows you to reuse device names.  
To view unassigned virtual MFA devices in your account, you can use either the [list-virtual-mfa-devices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-virtual-mfa-devices.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html) call.
To deactivate a virtual MFA device, you can use either the [deactivate-mfa-device](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html) call. The device will become unassigned.
To attach an unassigned virtual MFA device to your AWS account root user or IAM users, you'll need the authentication code generated by the device along with either the [enable-mfa-device](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-mfa-device.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) call.

### Hardware TOTP tokens


A hardware device generates a six-digit numeric code based on the [time-based one-time password (TOTP) algorithm](https://datatracker.ietf.org/doc/html/rfc6238). The user must type a valid code from the device on a second webpage during sign-in.

These tokens are used exclusively with AWS accounts. You can only use tokens that have their unique token seeds shared securely with AWS. Token seeds are secret keys generated at the time of token production. Tokens purchased from other sources will not function with IAM. To ensure compatibility, you must purchase your hardware MFA device from one of the following links: [OTP token](https://www.amazon.com/SafeNet-IDProve-Time-based-6-Digit-Services/dp/B002CRN5X8) or [OTP display card](https://www.amazon.com/SafeNet-IDProve-Card-Amazon-Services/dp/B00J4NGUO4).
+ Each MFA device assigned to a user must be unique. A user cannot type a code from another user's device to be authenticated. For information on supported hardware MFA devices, see [Multi-Factor Authentication (MFA)](https://aws.amazon.com/iam/features/mfa/?audit=2019q1).
+ If you want to use a physical MFA device, we recommend that you use security keys as an alternative to hardware TOTP devices. Security keys have no battery requirements, are phishing resistant, and support multiple users on a single device.

You can enable a passkey or security key from the AWS Management Console only, not from the AWS CLI or AWS API. Before you can enable a security key, you must have physical access to the device.

For instructions on setting up a hardware TOTP token for an IAM user, see [Assign a hardware TOTP token in the AWS Management Console](id_credentials_mfa_enable_physical.md).

**Note**  
**SMS text message-based MFA** – AWS ended support for enabling SMS multi-factor authentication (MFA). We recommend that customers who have IAM users that use SMS text message-based MFA switch to one of the following alternative methods: [Passkey or security key](id_credentials_mfa_enable_fido.md), [virtual (software-based) MFA device](id_credentials_mfa_enable_virtual.md), or [hardware MFA device](id_credentials_mfa_enable_physical.md). You can identify the users in your account with an assigned SMS MFA device. In the IAM console, choose **Users** from the navigation pane, and look for users with **SMS** in the **MFA** column of the table.

## MFA recommendations


To help secure your AWS identities, follow these recommendations for MFA authentication. 
+ We recommend that you use phishing-resistant MFA, such as [passkeys and security keys](#passkeys-security-keys-for-iam-users), as your MFA device. These FIDO-based authenticators provide the strongest protection against attacks such as phishing.
+ We recommend that you enable multiple MFA devices to the AWS account root user and IAM users in your AWS accounts. This allows you to raise the security bar in your AWS accounts and simplify managing access to highly privileged users, such as the AWS account root user.
+ You can register up to **eight** MFA devices of any combination of the [ currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) with your AWS account root user and IAM users. With multiple MFA devices, you only need one MFA device to sign in to the AWS Management Console or create a session through the AWS CLI as that user. An IAM user must authenticate with an existing MFA device to enable or disable an additional MFA device.
+ In the event of a lost, stolen, or inaccessible MFA device you can use one of the remaining MFA devices to access the AWS account without performing the AWS account recovery procedure. If an MFA device is lost or stolen, it should be disassociated from the IAM principal with which it is associated.
+ The use of multiple MFAs allows your employees in geographically dispersed locations or working remotely to use hardware-based MFA to access AWS without having to coordinate the physical exchange of a single hardware device between employees.
+ The use of additional MFA devices for IAM principals allows you to use one or more MFAs for everyday usage, while also maintaining physical MFA devices in a secure physical location such as a vault or safe for backup and redundancy.

**Notes**  
You cannot pass the MFA information for a security key or passkey to AWS STS API operations to request temporary credentials. You can obtain credentials for use with the AWS CLI and AWS SDKs when using a security key or passkey by running the `aws login` command.
You cannot use AWS CLI commands or AWS API operations to enable [FIDO security keys](id_credentials_mfa_enable_fido.md).
You cannot use the same name for more than one root user or IAM MFA device.

## Additional resources


The following resources can help you learn more about MFA.
+ For more information about using MFA to access AWS, see [MFA enabled sign-in](console_sign-in-mfa.md).
+  You can leverage IAM Identity Center to enable secure MFA access to your AWS access portal, IAM Identity Center integrated apps, and the AWS CLI. For more information, see [Enable MFA in IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/mfa-getting-started.html).

# Assign a passkey or security key in the AWS Management Console
Assign a passkey or security key

Passkeys are a type of [multi-factor authentication (MFA) device](id_credentials_mfa.md) that you can use to protect your AWS resources. AWS supports synced passkeys and device-bound passkeys also known as security keys. 

Synced passkeys allow IAM users to access their FIDO sign-in credentials on many of their devices, even new ones, without having to re-enroll every device on every account. Synced passkeys include first-party credential managers like Google, Apple, and Microsoft and third-party credential managers such as 1Password, Dashlane, and Bitwarden as a second factor. You can also use on-device biometrics (e.g., TouchID, FaceID) to unlock your chosen credential manager to use passkeys. 

Alternatively, device-bound passkeys are bound to a FIDO security key that you plug into a USB port on your computer and then tap when prompted to securely complete the sign-in process. If you already use a FIDO security key with other services, and it has an [AWS supported configuration](id_credentials_mfa_fido_supported_configurations.md) (for example, the YubiKey 5 Series from Yubico), you can also use it with AWS. Otherwise, you need to purchase a FIDO security key if you want to use WebAuthn for MFA in AWS. Additionally, FIDO security keys can support multiple IAM or root users on the same device, enhancing their utility for account security. For specifications and purchase information for both device types, see [Multi-Factor Authentication](http://aws.amazon.com/iam/details/mfa/).

You can register up to **eight** MFA devices of any combination of the [currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) with your AWS account root user and IAM users. With multiple MFA devices, you only need one MFA device to sign in to the AWS Management Console or create a session through the AWS CLI as that user. We recommend that you register multiple MFA devices. For example, you can register a built-in authenticator and also register a security key that you keep in a physically secure location. If you’re unable to use your built-in authenticator, then you can use your registered security key. For authenticator applications, we also recommend enabling the cloud backup or sync feature in those apps to help you avoid losing access to your account if you lose or break your device with the authenticator apps.

**Note**  
We recommend that you require your human users to use temporary credentials when accessing AWS. Your users can federate into AWS with an identity provider where they authenticate with their corporate credentials and MFA configurations. To manage access to AWS and business applications, we recommend that you use IAM Identity Center. For more information, see the [IAM Identity Center User Guide](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html). 

**Topics**
+ [

## Permissions required
](#enable-fido-mfa-for-iam-user-permissions-required)
+ [

## Enable a passkey or security key for your own IAM user (console)
](#enable-fido-mfa-for-own-iam-user)
+ [

## Enable a passkey or security key for another IAM user (console)
](#enable-fido-mfa-for-iam-user)
+ [

## Replace a passkey or security key
](#replace-fido-mfa)
+ [

# Supported configurations for using passkeys and security keys
](id_credentials_mfa_fido_supported_configurations.md)

## Permissions required


To manage a FIDO passkey for your own IAM user while protecting sensitive MFA-related actions, you must have the permissions from the following policy:

**Note**  
The ARN values are static values and are not an indicator of what protocol was used to register the authenticator. We have deprecated U2F, so all new implementations use WebAuthn.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowManageOwnUserMFA",
            "Effect": "Allow",
            "Action": [
                "iam:DeactivateMFADevice",
                "iam:EnableMFADevice",
                "iam:GetUser",
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        },
        {
            "Sid": "DenyAllExceptListedIfNoMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:EnableMFADevice",
                "iam:GetUser",
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}
```

------

## Enable a passkey or security key for your own IAM user (console)


You can enable a passkey or security key for your own IAM user from the AWS Management Console only, not from the AWS CLI or AWS API. Before you can enable a security key, you must have physical access to the device.

**To enable a passkey or security key for your own IAM user (console)**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. On the selected IAM user's page, choose the **Security credentials** tab.

1. Under **Multi-factor authentication (MFA)**, choose **Assign MFA device**.

1. On the **MFA device name** page, enter a **Device name**, choose **Passkey or Security Key**, and then choose **Next**.

1. On **Set up device**, set up your passkey. Create a passkey with biometric data like your face or fingerprint, with a device pin, or by inserting the FIDO security key into your computer's USB port and tapping it.

1. Follow the instructions on your browser and then choose **Continue**.

You have now registered your passkey or security key for use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md). 

## Enable a passkey or security key for another IAM user (console)


You can enable a passkey or security for another IAM user from the AWS Management Console only, not from the AWS CLI or AWS API.

**To enable a passkey or security for another IAM user (console)**

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, choose **Users**.

1. Under **Users**, choose the name of the user for whom you want to enable MFA.

1. On the selected IAM user page, choose the **Security Credentials** tab. 

1. Under **Multi-factor authentication (MFA)**, choose **Assign MFA device**.

1. On the **MFA device name** page, enter a **Device name**, choose **Passkey or Security Key**, and then choose **Next**.

1. On **Set up device**, set up your passkey. Create a passkey with biometric data like your face or fingerprint, with a device pin, or by inserting the FIDO security key into your computer's USB port and tapping it.

1. Follow the instructions on your browser and then choose **Continue**.

You have now registered a passkey or security key for another IAM user to use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md).

## Replace a passkey or security key


You can have up to eight MFA devices of any combination of the [ currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) assigned to a user at a time with your AWS account root user and IAM users. If the user loses a FIDO authenticator or needs to replace it for any reason, you must first deactivate the old FIDO authenticator. Then you can add a new MFA device for the user.
+ To deactivate the device currently associated with an IAM user, see [Deactivate an MFA device](id_credentials_mfa_disable.md).
+ To add a new FIDO security key for an IAM user, see [Enable a passkey or security key for your own IAM user (console)](#enable-fido-mfa-for-own-iam-user).

If you don't have access to a new passkey or security key, you can enable a new virtual MFA device or hardware TOTP token. See one of the following for instructions:
+ [Assign a virtual MFA device in the AWS Management Console](id_credentials_mfa_enable_virtual.md) 
+ [Assign a hardware TOTP token in the AWS Management Console](id_credentials_mfa_enable_physical.md) 

# Supported configurations for using passkeys and security keys


You can use FIDO2 device-bound passkeys, also known as security keys, as a multi-factor authentication (MFA) method with IAM using currently supported configurations. These include FIDO2 devices supported by IAM and browsers that support FIDO2. Before you register your FIDO2 device, check that you’re using the latest browser and operating system (OS) version. Features may behave differently across different browsers, authenticators, and OS clients. If your device registration fails on one browser, you can try to register with another browser. 

FIDO2 is an open authentication standard and an extension of FIDO U2F, offering the same high level of security based on public key cryptography. FIDO2 consists of the W3C Web Authentication specification (WebAuthn API) and the FIDO Alliance Client-to-Authenticator Protocol (CTAP), an application layer protocol. CTAP enables communication between client or platform, like a browser or operating system, with an external authenticator. When you enable a FIDO Certified authenticator in AWS, the security key creates a new key pair for use with only AWS. First, you enter your credentials. When prompted, you tap the security key, which responds to the authentication challenge issued by AWS. To learn more about the FIDO2 standard, see the [FIDO2 Project](https://en.wikipedia.org/wiki/FIDO2_Project).

## FIDO2 devices supported by AWS


IAM supports FIDO2 security devices that connect to your devices through USB, Bluetooth, or NFC. IAM also supports platform authenticators such as TouchID or FaceID. IAM does not support local passkey registration for Windows Hello. To create and use passkeys, Windows users should use [cross-device authentication](https://passkeys.dev/docs/reference/terms/#cross-device-authentication-cda) where you use a passkey from one device like a mobile device or hardware security key to sign in on another device like a laptop.

**Note**  
AWS requires access to the physical USB port on your computer to verify your FIDO2 device. Security keys will not work with a virtual machine, a remote connection, or a browser's incognito mode.

The FIDO Alliance maintains a list of all [FIDO2 products](https://fidoalliance.org/certification/fido-certified-products/) that are compatible with FIDO specifications.

## Browsers that support FIDO2


The availability of FIDO2 security devices that run in a web browser depends on the combination of browser and operating system. The following browsers currently support the use of security keys:


****  

| Web browser | macOS 10.15\$1 | Windows 10 | Linux | iOS 14.5\$1 | Android 7\$1 | 
| --- | --- | --- | --- | --- | --- | 
| Chrome | Yes | Yes | Yes | Yes | No | 
| Safari | Yes | No | No | Yes | No | 
| Edge | Yes | Yes | No | Yes | No | 
| Firefox | Yes | Yes | No | Yes | No | 

**Note**  
Most Firefox versions that currently support FIDO2 don't enable support by default. For instructions on enabling FIDO2 support in Firefox, see [Troubleshoot Passkeys and FIDO Security Keys](troubleshoot_mfa-fido.md).  
Firefox on macOS may not fully support cross-device authentication workflows for passkeys. You may get a prompt to touch a security key instead of proceeding with cross-device authentication. We recommend using a different browser, such as Chrome or Safari, for signing in with passkeys on macOS.

For more information about browser support for a FIDO2-Certified device like YubiKey, see [Operating system and web browser support for FIDO2 and U2F](https://support.yubico.com/hc/en-us/articles/360016615020-Operating-system-and-web-browser-support-for-FIDO2-and-U2F).

### Browser plugins


AWS supports only browsers that natively support FIDO2. AWS doesn't support using plugins to add FIDO2 browser support. Some browser plugins are incompatible with the FIDO2 standard and can cause unexpected results with FIDO2 security keys. 

For information on disabling browser plugins and other troubleshooting tips, see [I can't enable my FIDO security key](troubleshoot_mfa-fido.md#troubleshoot_mfa-fido-cant-enable). 

## Device certifications


We capture and assign device-related certifications, such as FIPS validation and FIDO certification level, only during the registration of a security key. Your device certification is retrieved from the [FIDO Alliance Metadata Service (MDS)](https://fidoalliance.org/metadata/). If the certification status or level of your security key changes, it will not be reflected in the device tags automatically. To update the certification information of a device, register the device again to fetch the updated certification information. 

AWS provides the following certification types as condition keys during device registration, obtained from the FIDO MDS: FIPS-140-2, FIPS-140-3, and FIDO certification levels. You have the ability to specify the registration of specific authenticators in their IAM policies, based on your preferred certification type and level. For more information, see the policies below.

### Example policies for device certifications


The following use cases show sample policies that allow you to register MFA devices with FIPS certifications.

**Topics**
+ [

#### Use case 1: Allow registering only devices that have FIPS-140-2 L2 certifications
](#id_credentials_mfa_fido_certifications_policies_use_case_1)
+ [

#### Use case 2: Allow registering devices that have FIPS-140-2 L2 and FIDO L1 certifications
](#id_credentials_mfa_fido_certifications_policies_use_case_2)
+ [

#### Use case 3: Allow registering devices that have either FIPS-140-2 L2 or FIPS-140-3 L2 certifications
](#id_credentials_mfa_fido_certifications_policies_use_case_3)
+ [

#### Use case 4: Allow registering devices that have FIPS-140-2 L2 certification and support other MFA types like virtual authenticators and hardware TOTP
](#id_credentials_mfa_fido_certifications_policies_use_case_4)

#### Use case 1: Allow registering only devices that have FIPS-140-2 L2 certifications


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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Create"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Activate",
                    "iam:FIDO-FIPS-140-2-certification": "L2"
                }
            }
        }
    ]
}
```

------

#### Use case 2: Allow registering devices that have FIPS-140-2 L2 and FIDO L1 certifications


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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Create"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Activate",
                    "iam:FIDO-FIPS-140-2-certification": "L2",
                    "iam:FIDO-certification": "L1"
                }
            }
        }
    ]
}
```

------

#### Use case 3: Allow registering devices that have either FIPS-140-2 L2 or FIPS-140-3 L2 certifications


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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Create"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Activate",
                    "iam:FIDO-FIPS-140-2-certification": "L2"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "iam:EnableMFADevice",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:RegisterSecurityKey" : "Activate",
                    "iam:FIDO-FIPS-140-3-certification": "L2"
                }
            }
        }
    ]
}
```

------

#### Use case 4: Allow registering devices that have FIPS-140-2 L2 certification and support other MFA types like virtual authenticators and hardware TOTP


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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iam:EnableMFADevice",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "iam:RegisterSecurityKey": "Create"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "iam:EnableMFADevice",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "iam:RegisterSecurityKey": "Activate",
          "iam:FIDO-FIPS-140-2-certification": "L2"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "iam:EnableMFADevice",
      "Resource": "*",
      "Condition": {
        "Null": {
          "iam:RegisterSecurityKey": "true"
        }
      }
    }
  ]
}
```

------

## AWS CLI and AWS API


AWS supports using passkeys and security keys only in the AWS Management Console. Using passkeys and security keys for MFA is not supported in the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/) and [AWS API](https://aws.amazon.com/tools/), or for access to [MFA-protected API operations](id_credentials_mfa_configure-api-require.md).

## Additional resources

+ For more information on using passkeys and security keys in AWS, see [Assign a passkey or security key in the AWS Management Console](id_credentials_mfa_enable_fido.md).
+ For help with troubleshooting passkeys and security keys in AWS, see [Troubleshoot Passkeys and FIDO Security Keys](troubleshoot_mfa-fido.md).
+ For general industry information on FIDO2 support, see [FIDO2 Project](https://en.wikipedia.org/wiki/FIDO2_Project). 

# Assign a virtual MFA device in the AWS Management Console
Assign a virtual MFA device

**Important**  
AWS recommends that you use a passkey or security key for MFA to AWS, wherever possible. For more information, see [Assign a passkey or security key in the AWS Management Console](id_credentials_mfa_enable_fido.md).

You can use a phone or other device as a virtual multi-factor authentication (MFA) device. To do this, install a mobile app that is compliant with [RFC 6238, a standards-based TOTP (time-based one-time password) algorithm](https://datatracker.ietf.org/doc/html/rfc6238). These apps generate a six-digit authentication code. Because authenticators can run on unsecured mobile devices, and the codes could potentially be shared with unauthorized parties, TOTP-based MFA does not provide the same level of security as phishing-resistant options such as [FIDO2](https://en.wikipedia.org/wiki/FIDO_Alliance#FIDO2) security keys and passkeys. We recommend that you use passkeys or security keys for MFA for the strongest protection against attacks such as phishing.

If you are not yet able to use passkeys or security keys, we recommend that you use a virtual MFA device as an interim measure while you wait for any hardware purchase approvals or for your hardware to arrive.

Most virtual MFA apps support creating multiple virtual devices, allowing you to use the same app for multiple AWS accounts or users. You can register up to **eight** MFA devices of any combination of [MFA types](https://aws.amazon.com/iam/features/mfa/) with your AWS account root user and IAM users. You only need one MFA device to sign in to the AWS Management Console or create a session through the AWS CLI. We recommend that you register multiple MFA devices. For authenticator applications, we also recommend enabling the cloud backup or sync feature to help you avoid losing access to your account if you lose or break your device.

AWS requires a virtual MFA app that produces a six-digit OTP. For a list of virtual MFA apps that you can use, see [Multi-Factor Authentication](https://aws.amazon.com/iam/features/mfa/?audit=2019q1). 

**Topics**
+ [

## Permissions required
](#mfa_enable_virtual_permissions-required)
+ [

## Enable a virtual MFA device for an IAM user (console)
](#enable-virt-mfa-for-iam-user)
+ [

## Replace a virtual MFA device
](#replace-virt-mfa)

## Permissions required


To manage virtual MFA devices for your IAM user, you must have the permissions from the following policy: [AWS: Allows MFA-authenticated IAM users to manage their own MFA device on the Security credentials page](reference_policies_examples_aws_my-sec-creds-self-manage-mfa-only.md).

## Enable a virtual MFA device for an IAM user (console)


You can use IAM in the AWS Management Console to enable and manage a virtual MFA device for an IAM user in your account. You can attach tags to your IAM resources, including virtual MFA devices, to identify, organize, and control access to them. You can tag virtual MFA devices only when you use the AWS CLI or AWS API. To enable and manage an MFA device using the AWS CLI or AWS API, see [Assign MFA devices in the AWS CLI or AWS API](id_credentials_mfa_enable_cliapi.md). For more information about tagging IAM resources, see [Tags for AWS Identity and Access Management resources](id_tags.md). 

**Note**  
You must have physical access to the hardware that will host the user's virtual MFA device in order to configure MFA. For example, you might configure MFA for a user who will use a virtual MFA device running on a smartphone. In that case, you must have the smartphone available in order to finish the wizard. Because of this, you might want to let users configure and manage their own virtual MFA devices. In that case, you must grant users the permissions to perform the necessary IAM actions. For more information and for an example of an IAM policy that grants these permissions, see the [IAM tutorial: Permit users to manage their credentials and MFA settings](tutorial_users-self-manage-mfa-and-creds.md) and example policy [AWS: Allows MFA-authenticated IAM users to manage their own MFA device on the Security credentials page](reference_policies_examples_aws_my-sec-creds-self-manage-mfa-only.md). 

**To enable a virtual MFA device for an IAM user (console)**

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, choose **Users**.

1. In the **Users** list, choose the name of the IAM user.

1. Choose the **Security Credentials** tab. Under **Multi-factor authentication (MFA)**, choose **Assign MFA device**.

1. In the wizard, type a **Device name**, choose **Authenticator app**, and then choose **Next**.

   IAM generates and displays configuration information for the virtual MFA device, including a QR code graphic. The graphic is a representation of the "secret configuration key" that is available for manual entry on devices that do not support QR codes.

1. Open your virtual MFA app. For a list of apps that you can use for hosting virtual MFA devices, see [Multi-Factor Authentication](http://aws.amazon.com/iam/details/mfa/). 

   If the virtual MFA app supports multiple virtual MFA devices or accounts, choose the option to create a new virtual MFA device or account.

1. Determine whether the MFA app supports QR codes, and then do one of the following:
   + From the wizard, choose **Show QR code**, and then use the app to scan the QR code. This might be a camera icon or **Scan code** option that uses the device's camera to scan the code.
   + From the wizard, choose **Show secret key**, and then type the secret key into your MFA app.

   When you are finished, the virtual MFA device starts generating one-time passwords. 

1. On the **Set up device** page, in the **MFA code 1** box, type the one-time password that currently appears in the virtual MFA device. Wait up to 30 seconds for the device to generate a new one-time password. Then type the second one-time password into the **MFA code 2** box. Choose **Add MFA**. 
**Important**  
Submit your request immediately after generating the codes. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device is out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can [resync the device](id_credentials_mfa_sync.md).

The virtual MFA device is now ready for use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md).

**Note**  
Unassigned virtual MFA devices in your AWS account are deleted when you’re adding new virtual MFA devices either via the AWS Management Console or during the sign-in process. Unassigned virtual MFA devices are devices in your account but not used by account root user or IAM users for the sign-in process. They’re deleted so new virtual MFA devices can be added to your account. It also allows you to reuse device names.  
To view unassigned virtual MFA devices in your account, you can use either the [list-virtual-mfa-devices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-virtual-mfa-devices.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html) call.
To deactivate a virtual MFA device, you can use either the [deactivate-mfa-device](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html) call. The device will become unassigned.
To attach an unassigned virtual MFA device to your AWS account root user or IAM users, you'll need the authentication code generated by the device along with either the [enable-mfa-device](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-mfa-device.html) AWS CLI command or [API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) call.

## Replace a virtual MFA device


Your AWS account root user and IAM users can register up to **eight** MFA devices of any combination of MFA types. If the user loses a device or needs to replace it for any reason, deactivate the old device. Then you can add the new device for the user.
+ To deactivate the device currently associated with another IAM user, see [Deactivate an MFA device](id_credentials_mfa_disable.md).
+ To add a replacement virtual MFA device for another IAM user, follow the steps in the procedure [Enable a virtual MFA device for an IAM user (console)](#enable-virt-mfa-for-iam-user) above.
+ To add a replacement virtual MFA device for the AWS account root user, follow the steps in the procedure [Enable a virtual MFA device for the root user (console)](enable-virt-mfa-for-root.md).

# Assign a hardware TOTP token in the AWS Management Console
Assign a hardware TOTP token

**Important**  
AWS recommends that you use a passkey or security key for MFA to AWS, wherever possible. For more information, see [Assign a passkey or security key in the AWS Management Console](id_credentials_mfa_enable_fido.md).

A hardware TOTP token generates a six-digit numeric code based upon a time-based one-time password (TOTP) algorithm. The user must type a valid code from the device when prompted during the sign-in process. Each MFA device assigned to a user must be unique; a user cannot type a code from another user's device to be authenticated. MFA devices cannot be shared across accounts or users.

Hardware TOTP tokens and [FIDO security keys](id_credentials_mfa_enable_fido.md) are both physical devices that you purchase. Hardware MFA devices generate TOTP codes for authentication when you sign in to AWS. They rely on batteries, which may need replacement and resynchronization with AWS over time. FIDO security keys, which utilize public key cryptography, do not require batteries and offer a seamless authentication process. We recommend using FIDO security keys for their phishing resistance, which provides a more secure alternative to TOTP devices. Additionally, FIDO security keys can support multiple IAM or root users on the same device, enhancing their utility for account security. For specifications and purchase information for both device types, see [Multi-Factor Authentication](http://aws.amazon.com/iam/details/mfa/).



You can enable a hardware TOTP token for an IAM user from the AWS Management Console, the command line, or the IAM API. To enable an MFA device for your AWS account root user, see [Enable a hardware TOTP token for the root user (console)](enable-hw-mfa-for-root.md).

You can register up to **eight** MFA devices of any combination of the [ currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) with your AWS account root user and IAM users. With multiple MFA devices, you only need one MFA device to sign in to the AWS Management Console or create a session through the AWS CLI as that user.

**Important**  
We recommend that you enable multiple MFA devices for your users for continued access to your account in case of a lost or inaccessible MFA device.

**Note**  
If you want to enable the MFA device from the command line, use [https://docs.aws.amazon.com/cli/latest/reference/iam/enable-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/enable-mfa-device.html). To enable the MFA device with the IAM API, use the [https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) operation. 

**Topics**
+ [

## Permissions required
](#enable-hw-mfa-for-iam-user-permissions-required)
+ [

## Enable a hardware TOTP token for your own IAM user (console)
](#enable-hw-mfa-for-own-iam-user)
+ [

## Enable a hardware TOTP token for another IAM user (console)
](#enable-hw-mfa-for-iam-user)
+ [

## Replace a physical MFA device
](#replace-phys-mfa)

## Permissions required


To manage a hardware TOTP token for your own IAM user while protecting sensitive MFA-related actions, you must have the permissions from the following policy:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowManageOwnUserMFA",
            "Effect": "Allow",
            "Action": [
                "iam:DeactivateMFADevice",
                "iam:EnableMFADevice",
                "iam:GetUser",
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        },
        {
            "Sid": "DenyAllExceptListedIfNoMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:EnableMFADevice",
                "iam:GetUser",
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}
```

------

## Enable a hardware TOTP token for your own IAM user (console)


 You can enable your own hardware TOTP token from the AWS Management Console.

**Note**  
Before you can enable a hardware TOTP token, you must have physical access to the device.

**To enable a hardware TOTP token for your own IAM user (console)**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. On the **AWS IAM credentials** tab, in the **Multi-factor authentication (MFA)** section, choose **Assign MFA device**.

1. In the wizard, type a **Device name**, choose **Hardware TOTP token**, and then choose **Next**.

1. Type the device serial number. The serial number is usually on the back of the device.

1. In the **MFA code 1** box, type the six-digit number displayed by the MFA device. You might need to press the button on the front of the device to display the number.  
![\[IAM Dashboard, MFA Device\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/MFADevice.png)

1. Wait 30 seconds while the device refreshes the code, and then type the next six-digit number into the **MFA code 2** box. You might need to press the button on the front of the device again to display the second number.

1. Choose **Add MFA**.
**Important**  
Submit your request immediately after generating the authentication codes. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device becomes out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can [resync the device](id_credentials_mfa_sync.md).

The device is ready for use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md).

## Enable a hardware TOTP token for another IAM user (console)


 You can enable a hardware TOTP token for another IAM user from the AWS Management Console.

**To enable a hardware TOTP token for another IAM user (console)**

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, choose **Users**.

1. Choose the name of the user for whom you want to enable MFA.

1. Choose the **Security Credentials** tab. Under **Multi-factor authentication (MFA)**, choose **Assign MFA device**.

1. In the wizard, type a **Device name**, choose **Hardware TOTP token**, and then choose **Next**.

1. Type the device serial number. The serial number is usually on the back of the device.

1. In the **MFA code 1** box, type the six-digit number displayed by the MFA device. You might need to press the button on the front of the device to display the number.  
![\[IAM Dashboard, MFA Device\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/MFADevice.png)

1. Wait 30 seconds while the device refreshes the code, and then type the next six-digit number into the **MFA code 2** box. You might need to press the button on the front of the device again to display the second number.

1. Choose **Add MFA**.
**Important**  
Submit your request immediately after generating the authentication codes. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device becomes out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can [resync the device](id_credentials_mfa_sync.md).

The device is ready for use with AWS. For information about using MFA with the AWS Management Console, see [MFA enabled sign-in](console_sign-in-mfa.md).

## Replace a physical MFA device


You can have up to eight MFA devices of any combination of the [currently supported MFA types](https://aws.amazon.com/iam/features/mfa/) assigned to a user at a time with your AWS account root user and IAM users. If the user loses a device or needs to replace it for any reason, you must first deactivate the old device. Then you can add the new device for the user.
+ To deactivate the device currently associated with a user, see [Deactivate an MFA device](id_credentials_mfa_disable.md).
+ To add a replacement hardware TOTP token for an IAM user, follow the steps in the procedure [Enable a hardware TOTP token for another IAM user (console)](#enable-hw-mfa-for-iam-user) earlier in this topic.
+ To add a replacement hardware TOTP token for the AWS account root user, follow the steps in the procedure [Enable a hardware TOTP token for the root user (console)](enable-hw-mfa-for-root.md) earlier in this topic.

# Assign MFA devices in the AWS CLI or AWS API


You can use AWS CLI commands or AWS API operations to enable a virtual MFA device for an IAM user. You cannot enable an MFA device for the AWS account root user with the AWS CLI, AWS API, Tools for Windows PowerShell, or any other command line tool. However, you can use the AWS Management Console to enable an MFA device for the root user. 

When you enable an MFA device from the AWS Management Console, the console performs multiple steps for you. If you instead create a virtual device using the AWS CLI, Tools for Windows PowerShell, or AWS API, then you must perform the steps manually and in the correct order. For example, to create a virtual MFA device, you must create the IAM object and extract the code as either a string or a QR code graphic. Then you must sync the device and associate it with an IAM user. See the **Examples** section of [New-IAMVirtualMFADevice](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=New-IAMVirtualMFADevice.html&tocid=New-IAMVirtualMFADevice) for more details. For a physical device, you skip the creation step and go directly to syncing the device and associating it with the user. 

You can attach tags to your IAM resources, including virtual MFA devices, to identify, organize, and control access to them. You can tag virtual MFA devices only when you use the AWS CLI or AWS API.

An IAM user using the SDK or CLI can enable an additional MFA device by calling [https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) or deactivate an existing MFA device by calling [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html). To do this successfully, they must first call [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) and submit MFA codes with an existing MFA device. This call returns temporary security credentials that can then be used to sign API operations that require MFA authentication. For an example request and response, see [`GetSessionToken`—temporary credentials for users in untrusted environments](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken). 

**To create the virtual device entity in IAM to represent a virtual MFA device**  
These commands provide an ARN for the device that is used in place of a serial number in many of the following commands.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/create-virtual-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-virtual-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateVirtualMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateVirtualMFADevice.html) 

**To enable an MFA device for use with AWS**  
These commands synchronize the device with AWS and associate it with a user. If the device is virtual, use the ARN of the virtual device as the serial number.

**Important**  
Submit your request immediately after generating the authentication codes. If you generate the codes and then wait too long to submit the request, the MFA device successfully associates with the user but the MFA device becomes out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time. If this happens, you can resynchronize the device using the commands described below.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/enable-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/enable-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) 

**To deactivate a device**  
Use these commands to disassociate the device from the user and deactivate it. If the device is virtual, use the ARN of the virtual device as the serial number. You must also separately delete the virtual device entity. 
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/deactivate-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/deactivate-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html)

**To list virtual MFA device entities**  
Use these commands to list virtual MFA device entities.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/list-virtual-mfa-devices.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-virtual-mfa-devices.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html) 

**To tag a virtual MFA device**  
Use these commands to tag a virtual MFA device.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/tag-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagMFADevice.html) 

**To list tags for a virtual MFA device**  
Use these commands to list the tags attached to a virtual MFA device.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/list-mfa-device-tags.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-mfa-device-tags.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADeviceTags.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADeviceTags.html) 

**To untag a virtual MFA device**  
Use these commands to remove tags attached to a virtual MFA device.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/untag-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagMFADevice.html) 

**To resynchronize an MFA device**  
Use these commands if the device is generating codes that are not accepted by AWS. If the device is virtual, use the ARN of the virtual device as the serial number.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/resync-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/resync-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResyncMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResyncMFADevice.html) 

**To delete a virtual MFA device entity in IAM**  
After the device is disassociated from the user, you can delete the device entity.
+ AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-virtual-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-virtual-mfa-device.html) 
+ AWS API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteVirtualMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteVirtualMFADevice.html) 

**To recover a virtual MFA device that is lost or not working**  
Sometimes, a user's device that hosts the virtual MFA app is lost, replaced, or not working. When this happens, the user can't recover it on their own. The user must contact an administrator to deactivate the device. For more information, see [Recover an MFA protected identity in IAM](id_credentials_mfa_lost-or-broken.md).

# Check MFA status


Use the IAM console to check whether an AWS account root user or IAM user has a valid MFA device enabled.

**To check the MFA status of a root user**

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

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.

1. Check under **Multi-factor Authentication (MFA)** to see whether MFA is enabled or disabled. If MFA has not been activated, an alert symbol (![\[Alert icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-alert-icon.console.png)) is displayed. 

If you want to enable MFA for the account, see one of the following:
+ [Enable a virtual MFA device for the root user (console)](enable-virt-mfa-for-root.md)
+ [Enable a passkey or security key for the root user (console)](enable-fido-mfa-for-root.md)
+ [Enable a hardware TOTP token for the root user (console)](enable-hw-mfa-for-root.md)

**To check the MFA status of IAM users**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/). 

1. In the navigation pane, choose **Users**.

1. If necessary, add the **MFA** column to the users table by completing the following steps:

   1. Above the table on the far right, choose the settings icon (![\[Settings icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)).

   1. In **Manage Columns**, select **MFA**.

   1. (Optional) Clear the checkbox for any column headings that you do not want to appear in the users table.

   1. Choose **Close** to return to the list of users.

1. The **MFA** column tells you about the MFA device that is enabled. If no MFA device is active for the user, the console displays **None**. If the user has an MFA device enabled, the **MFA** column shows the type of device that is enabled with a value of **Virtual**, **Security key**, **Hardware**, or **SMS**.
**Note**  
AWS ended support for enabling SMS multi-factor authentication (MFA). We recommend that customers who have IAM users that use SMS text message-based MFA switch to one of the following alternative methods: [virtual (software-based) MFA device](id_credentials_mfa_enable_virtual.md), [FIDO security key](id_credentials_mfa_enable_fido.md), or [hardware MFA device](id_credentials_mfa_enable_physical.md). You can identify the users in your account with an assigned SMS MFA device. To do so, go to the IAM console, choose **Users** from the navigation pane, and look for users with **SMS** in the **MFA** column of the table.

1. To view additional information about the MFA device for a user, choose the name of the user whose MFA status you want to check. Then choose the **Security credentials** tab. 

1. If no MFA device is active for the user, the console displays **No MFA devices. Assign an MFA device to improve the security of your AWS environment** in the **Multi-factor authentication (MFA)** section. If the user has MFA devices enabled, the **Multi-factor authentication (MFA)** section shows details about the devices:
   + The device name
   + The device type
   + The identifier for the device, such as a serial number for a physical device or the ARN in AWS for a virtual device
   + When the device was created

To remove or resync a device, choose the radio button next to the device and choose **Remove** or **Resync**.

For more information on enabling MFA, see the following: 
+ [Assign a virtual MFA device in the AWS Management Console](id_credentials_mfa_enable_virtual.md)
+ [Assign a passkey or security key in the AWS Management Console](id_credentials_mfa_enable_fido.md)
+ [Assign a hardware TOTP token in the AWS Management Console](id_credentials_mfa_enable_physical.md)

# Resynchronize virtual and hardware MFA devices


You can use AWS to resynchronize your virtual and hardware multi-factor authentication (MFA) devices. If your device is not synchronized when you try to use it, the sign-in attempt fails and IAM prompts you to resynchronize the device.

**Note**  
FIDO security keys do not go out of sync. If a FIDO security key is lost or broken, you can deactivate it. For instructions on deactivating any MFA device type, see [To deactivate an MFA device for another IAM user (console)](id_credentials_mfa_disable.md#deactivate-mfa-for-user).

As an AWS administrator, you can resynchronize your IAM users' virtual and hardware MFA devices if they get out of synchronization.

If your AWS account root user MFA device is not working, you can resynchronize your device using the IAM console with or without completing the sign-in process. If you aren’t able to successfully resynchronize your device, you may need to de-associate and re-associate it. For more information on how to do this, see [Deactivate an MFA device](id_credentials_mfa_disable.md) and [AWS Multi-factor authentication in IAM](id_credentials_mfa.md).

**Topics**
+ [

## Permissions required
](#id_credentials_mfa_sync_console-permissions-required)
+ [

## Resynchronizing virtual and hardware MFA devices (IAM console)
](#id_credentials_mfa_sync_console)
+ [

## Resynchronizing virtual and hardware MFA devices (AWS CLI)
](#id_credentials_mfa_sync_cli)
+ [

## Resynchronizing virtual and hardware MFA devices (AWS API)
](#id_credentials_mfa_sync_api)

## Permissions required


To resynchronize virtual or hardware MFA devices for your own IAM user, you must have the permissions from the following policy. This policy does not allow you to create or deactivate a device.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowListActions",
            "Effect": "Allow",
            "Action": [
                "iam:ListVirtualMFADevices"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowUserToViewAndManageTheirOwnUserMFA",
            "Effect": "Allow",
            "Action": [
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        },
        {
            "Sid": "BlockAllExceptListedIfNoMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:ListMFADevices",
                "iam:ListVirtualMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}
```

------

## Resynchronizing virtual and hardware MFA devices (IAM console)


You can use the IAM console to resynchronize virtual and hardware MFA devices.

**To resynchronize a virtual or hardware MFA device for your own IAM user (console)**

1. Use your AWS account ID or account alias, your IAM user name, and your password to sign in to the [IAM console](https://console.aws.amazon.com/iam).
**Note**  
For your convenience, the AWS sign-in page uses a browser cookie to remember your IAM user name and account information. If you previously signed in as a different user, choose **Sign in to a different account** near the bottom of the page to return to the main sign-in page. From there, you can type your AWS account ID or account alias to be redirected to the IAM user sign-in page for your account.

   To get your AWS account ID, contact your administrator.

1. In the navigation bar on the upper right, choose your user name, and then choose **Security credentials**.   
![\[AWS Management Console Security credentials link\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-user.shared.console.png)

1. On the **AWS IAM credentials** tab, in the **Multi-factor authentication (MFA)** section, choose the radio button next to the MFA device and choose **Resync**.

1. Type the next two sequentially generated codes from the device into **MFA code 1** and **MFA code 2**. Then choose **Resync**.
**Important**  
Submit your request immediately after generating the codes. If you generate the codes and then wait too long to submit the request, the request appears to work but the device remains out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time.

**To resynchronize a virtual or hardware MFA device for another IAM user (console)**

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, choose **Users**, and then choose the name of the user whose MFA device needs to be resynchronized.

1. Choose the **Security credentials** tab. In the **Multi-factor authentication (MFA)** section, choose the radio button next to the MFA device and choose **Resync**.

1. Type the next two sequentially generated codes from the device into **MFA code 1** and **MFA code 2**. Then choose **Resync**.
**Important**  
Submit your request immediately after generating the codes. If you generate the codes and then wait too long to submit the request, the request appears to work but the device remains out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time.

**To resynchronize your root user MFA before signing in (console)**

1. On the **Amazon Web Services Sign In With Authentication Device** page, choose **Having problems with your authentication device? Click here**.
**Note**  
You might see different text, such as **Sign in using MFA** and **Troubleshoot your authentication device**. However, the same features are provided.

1. In the **Re-Sync With Our Servers** section, type the next two sequentially generated codes from the device into **MFA code 1** and **MFA code 2**. Then choose **Re-sync authentication device**.

1. If necessary, type your password again and choose **Sign in**. Then complete the sign-in using your MFA device.

**To resynchronize your root user MFA device after signing in (console)**

1. Sign in to the [IAM console](https://console.aws.amazon.com/iam/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.
**Note**  
As the root user, you can't sign in to the **Sign in as IAM user** page. If you see the **Sign in as IAM user** page, choose **Sign in using root user email** near the bottom of the page. For help signing in as the root user, see [Signing in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-          root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. On the right side of the navigation bar, choose on your account name, and then choose **Security credentials**. If necessary, choose **Continue to Security credentials**.  
![\[Security credentials in the navigation menu\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-root.shared.console.png)

1. Expand the **Multi-factor authentication (MFA)** section on the page.

1. Choose the radio button next to the device and choose **Resync**.

1. In the **Resync MFA device** dialog box, type the next two sequentially generated codes from the device into **MFA code 1** and **MFA code 2**. Then choose **Resync**.
**Important**  
Submit your request immediately after generating the codes. If you generate the codes and then wait too long to submit the request, the MFA device is successfully associated with the user, but the MFA device is out of sync. This happens because time-based one-time passwords (TOTP) expire after a short period of time.

## Resynchronizing virtual and hardware MFA devices (AWS CLI)


You can resynchronize virtual and hardware MFA devices from the AWS CLI.

**To resynchronize a virtual or hardware MFA device for an IAM user (AWS CLI)**  
At a command prompt, issue the [aws iam resync-mfa-device](https://docs.aws.amazon.com/cli/latest/reference/iam/resync-mfa-device.html) command:
+ Virtual MFA device: Specify Amazon Resource Name (ARN) of device as the serial number.

  ```
  aws iam resync-mfa-device --user-name Richard --serial-number arn:aws:iam::123456789012:mfa/RichardsMFA --authentication-code1 123456 --authentication-code2 987654
  ```
+ Hardware MFA device: Specify hardware device's serial number as serial number. The format is vendor-specific. For example, you can purchase a gemalto token from Amazon. Its serial number is typically four letters followed by four numbers.

  ```
  aws iam resync-mfa-device --user-name Richard --serial-number ABCD12345678 --authentication-code1 123456 --authentication-code2 987654
  ```

**Important**  
Submit your request immediately after generating the codes. If you generate the codes and then wait too long to submit the request, the request fails because the codes expire after a short time.

## Resynchronizing virtual and hardware MFA devices (AWS API)


IAM has an API call that performs synchronization. In this case, we recommend that you give your virtual and hardware MFA device users permission to access this API call. Then build a tool based on that API call so your users can resynchronize their devices whenever they need to.

**To resynchronize a virtual or hardware MFA device for an IAM user (AWS API)**
+ Send the [ResyncMFADevice](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResyncMFADevice.html) request.

# Deactivate an MFA device


If you are having trouble signing in with a multi-factor authentication (MFA) device as an IAM user, contact your administrator for help.

As an administrator, you can deactivate the device for another IAM user. This allows the user to sign in without using MFA. You might do this as a temporary solution while the MFA device is replaced, or if the device is temporarily unavailable. However, we recommend that you enable a new device for the user as soon as possible. To learn how to enable a new MFA device, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md).

**Note**  
If you use the API or AWS CLI to delete a user from your AWS account, you must deactivate or delete the user's MFA device. You make this change as part of the process of removing the user. For more information about removing users, see [Remove or deactivate an IAM user](id_users_remove.md).

**Topics**
+ [

## Deactivating MFA devices (console)
](#deactive-mfa-console)
+ [

## Deactivating MFA devices (AWS CLI)
](#deactivate-mfa-cli)
+ [

## Deactivating MFA devices (AWS API)
](#deactivate-mfa-api)

## Deactivating MFA devices (console)
<a name="deactivate-mfa-for-user"></a>

**To deactivate an MFA device for another IAM user (console)**

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, choose **Users**.

1. To deactivate the MFA device for a user, choose the name of the user whose MFA you want to remove.

1. Choose the **Security credentials** tab.

1. Under **​Multi-factor authentication (MFA)**, choose the radio button next to the MFA device, choose **Remove**, and then choose **Remove**.

   The device is removed from AWS. It cannot be used to sign in or authenticate requests until it is reactivated and associated with an AWS user or AWS account root user.<a name="deactivate-mfa-for-root"></a>

**To deactivate the MFA device for your AWS account root user (console)**

1. Sign in to the [IAM console](https://console.aws.amazon.com/iam/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.
**Note**  
As the root user, you can't sign in to the **Sign in as IAM user** page. If you see the **Sign in as IAM user** page, choose **Sign in using root user email** near the bottom of the page. For help signing in as the root user, see [Signing in to the AWS Management Console as the root user](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-          root-user-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

1. On the right side of the navigation bar, choose on your account name, and then choose **Security credentials**. If necessary, choose **Continue to Security credentials**.  
![\[Security credentials in the navigation menu\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/security-credentials-root.shared.console.png)

1. In the **Multi-factor authentication (MFA)** section, choose the radio button next the MFA device that you want to deactivate and choose **Remove**.

1. Choose **Remove**.

   The MFA device is deactivated for the AWS account. Check the email that is associated with your AWS account for a confirmation message from Amazon Web Services. The email informs you that your Amazon Web Services multi-factor authentication (MFA) has been deactivated. The message will come from `@amazon.com` or `@aws.amazon.com`.

**Note**  
Unassigned virtual MFA devices in your AWS account are deleted when you’re adding new virtual MFA devices either via the AWS Management Console or during the sign-in process. Unassigned virtual MFA devices are devices in your account but not used by account root user or IAM users for the sign-in process. They’re deleted so new virtual MFA devices can be added to your account. It also allows you to reuse device names.

## Deactivating MFA devices (AWS CLI)


**To deactivate an MFA device for an IAM user (AWS CLI)**
+ Run this command: [https://docs.aws.amazon.com/cli/latest/reference/iam/deactivate-mfa-device.html](https://docs.aws.amazon.com/cli/latest/reference/iam/deactivate-mfa-device.html)

## Deactivating MFA devices (AWS API)


**To deactivate an MFA device for an IAM user (AWS API)**
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html)

# Recover an MFA protected identity in IAM
Recover an MFA protected identity

If your [virtual MFA device](id_credentials_mfa_enable_virtual.md) or [hardware TOTP token](id_credentials_mfa_enable_physical.md) appears to be functioning properly, but you can't use it to access your AWS resources, it might be out of synchronization with AWS. For information about synchronizing a virtual MFA device or hardware MFA device, see [Resynchronize virtual and hardware MFA devices](id_credentials_mfa_sync.md). [FIDO security keys](id_credentials_mfa_enable_fido.md) do not go out of sync.

If the [MFA device](id_credentials_mfa.md) for a AWS account root user is lost, damaged, or not working, you can recover access to your account. IAM users must contact an administrator to deactivate the device.

**Important**  
We recommend that you activate multiple MFA devices. Registering multiple MFA devices helps ensure continued access if a device is lost or broken. Your AWS account root user and IAM users can register up to eight MFA devices of any type.

## Prerequisite – Use another MFA device


If your [multi-factor authentication (MFA) device](id_credentials_mfa.md) is lost, damaged, or not working, you can sign in using another MFA device registered to the same root user or IAM user.

**To sign in using another MFA device**

1. Sign in to the [AWS Management Console](url-comsole-domain;iam) with your AWS account ID or account alias and password.

1. On the **Additional verification required** page or **Multi-factor authentication** page, choose **Try another MFA method**.

1. Authenticate with the type of MFA device that you selected.

1. The next step varies based on whether you successfully signed in with an alternate MFA device.
   + If you have successfully signed in, you can [Resynchronize virtual and hardware MFA devices](id_credentials_mfa_sync.md), which may resolve the issue. If your MFA device is lost or broken, you can deactivate it. For instructions on deactivating any MFA device type, see [Deactivate an MFA device](id_credentials_mfa_disable.md).
   + If you can't sign in with MFA, use the steps in [Recovering a root user MFA device](#root-mfa-lost-or-broken) or [Recovering an IAM user MFA device](#iam-user-mfa-lost-or-broken) to recover your MFA protected identity.



## Recovering a root user MFA device


If you can't sign in with MFA, you can use alternative methods of authentication to sign in by verifying your identity using the email and the primary contact phone number registered with your account.

Confirm you are able to access the email and primary contact phone number associated with your account before you use alternative authentication factors to sign in as a root user. If you need to update the primary contact phone number, sign in as an IAM user with *Administrator* access instead of the root user. For additional instructions on updating the account contact information, see [Editing contact information](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-contact-primary.html) in the *AWS Billing User Guide*. If you do not have access to an email and primary contact phone number, you must contact [AWS Support](https://support.aws.amazon.com/#/contacts/aws-mfa-support).

**Important**  
We recommend that you keep the email address and contact phone number linked to your root user up to date for a successful account recovery. For more information, see [Update the primary contact for your AWS account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-contact-primary.html) in the *AWS Account Management Reference Guide*.

**To sign in using alternative factors of authentication as an AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

1. On the **Additional verification required** page, select an MFA method to authenticate with and choose **Next**. 
**Note**  
You might see alternative text, such as **Sign in using MFA**, **Troubleshoot your authentication device**, or **Troubleshoot MFA**, but the functionality is the same. If you can't use alternative authentication factors to verify your account email address and primary contact phone number, contact [AWS Support](https://support.aws.amazon.com/#/contacts/aws-mfa-support) to deactivate your MFA device.

1. Depending on the type of MFA you are using, you will see a different page, but the **Troubleshoot MFA** option functions the same. On the **Additional verification required** page or **Multi-factor authentication** page, choose **Troubleshoot MFA**.

1. If required, type your password again and choose **Sign in**.

1. On the **Troubleshoot your authentication device** page, in the **Sign in using alternative factors of authentication** section, choose **Sign in using alternative factors**.

1. On the **Sign in using alternative factors of authentication** page, authenticate your account by verifying the email address, choose **Send verification email**. 

1. Check the email that is associated with your AWS account for a message from Amazon Web Services (recover-mfa-no-reply@verify.signin.aws). Follow the directions in the email.

   If you don't see the email in your account, check your spam folder, or return to your browser and choose **Resend the email**.

1. After you verify your email address, you can continue authenticating your account. To verify your primary contact phone number, choose **Call me now**.

1. Answer the call from AWS and, when prompted, enter the 6-digit number from the AWS website on your phone keypad. 

   If you don't receive a call from AWS, choose **Sign in **to sign in to the console again and start over. Or see [Lost or unusable Multi-Factor Authentication (MFA) device](https://support.aws.amazon.com/#/contacts/aws-mfa-support) to contact support for help.

1. After you verify your phone number, you can sign in to your account by choosing **Sign in to the console**.

1. The next step varies depending on the type of MFA you are using:
   + For a virtual MFA device, remove the account from your device. Then go to the [AWS Security Credentials](https://console.aws.amazon.com/iam/home?#security_credential) page and delete the old MFA virtual device entity before you create a new one.
   + For a FIDO security key, go to the [AWS Security Credentials](https://console.aws.amazon.com/iam/home?#security_credential) page and deactivate the old FIDO security key before enabling a new one.
   + For a hardware TOTP token, contact the third-party provider for help with fixing or replacing the device. You can continue to sign in using alternative factors of authentication until you receive your new device. After you have the new hardware MFA device, go to the [AWS Security Credentials](https://console.aws.amazon.com/iam/home?#security_credential) page and delete the old MFA device.
**Note**  
You don't have to replace a lost or stolen MFA device with the same type of device. For example, if you break your FIDO security key and order a new one, you can use virtual MFA or a hardware TOTP token until the new FIDO key arrives.

**Important**  
If your MFA device is missing or stolen, change your root user password after signing in and establishing your replacement MFA device. An attacker may have stolen the authentication device and might also have your current password. For more information, see [Change the password for the AWS account root user](root-user-password.md).

## Recovering an IAM user MFA device


If you are an IAM user that can't sign in with MFA, you can't recover an MFA device by yourself. You must contact an administrator to deactivate the device. Then you can enable a new device.

**To get help for an MFA device as an IAM user**

1. Contact the AWS administrator or other person who gave you the user name and password for the IAM user. The administrator must deactivate the MFA device as described in [Deactivate an MFA device](id_credentials_mfa_disable.md) so that you can sign in.

1. The next step varies depending on the type of MFA you are using:
   + For a virtual MFA device, remove the account from your device. Then enable the virtual device as described in [Assign a virtual MFA device in the AWS Management Console](id_credentials_mfa_enable_virtual.md).
   + For a FIDO security key, contact the third-party provider for help with replacing the device. When you receive the new FIDO security key, enable it as described in [Assign a passkey or security key in the AWS Management Console](id_credentials_mfa_enable_fido.md).
   + For a hardware TOTP token, contact the third-party provider for help with fixing or replacing the device. After you have the new physical MFA device, enable the device as described in [Assign a hardware TOTP token in the AWS Management Console](id_credentials_mfa_enable_physical.md).
**Note**  
You don't have to replace a lost or stolen MFA device with the same type of device. You can have up to eight MFA devices of any combination. For example, if you break your FIDO security key and order a new one, you can use virtual MFA or a hardware TOTP token until the new FIDO key arrives.

1. If your MFA device is missing or stolen, also change your password in case an attacker has stolen the authentication device and might also have your current password. For more information, see [Manage passwords for IAM users](id_credentials_passwords_admin-change-user.md)

# Secure API access with MFA


With IAM policies, you can specify which API operations a user is allowed to call. You can apply additional security by requiring users to authenticate with multi-factor authentication (MFA) before you allow them to perform particularly sensitive actions.

For example, you might have a policy that allows a user to perform the Amazon EC2 `RunInstances`, `DescribeInstances`, and `StopInstances` actions. But you might want to restrict a destructive action like `TerminateInstances` and ensure that users can perform that action only if they authenticate with an AWS MFA device.

**Topics**
+ [

## Overview
](#MFAProtectedAPI-overview)
+ [

## Scenario: MFA protection for cross-account delegation
](#MFAProtectedAPI-cross-account-delegation)
+ [

## Scenario: MFA protection for access to API operations in the current account
](#MFAProtectedAPI-user-mfa)
+ [

## Scenario: MFA protection for resources that have resource-based policies
](#MFAProtectedAPI-resource-policies)

## Overview


Adding MFA protection to API operations involves these tasks:

1. The administrator configures an AWS MFA device for each user who must make API requests that require MFA authentication. For more information, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md). 

1. The administrator creates policies for the users that include a `Condition` element that checks whether the user authenticated with an AWS MFA device.

1. The user calls one of the AWS STS API operations that support the MFA parameters: [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) or [GetSessionToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html). As part of the call, the user includes the device identifier for the device that's associated with the user. The user also includes the time-based one-time password (TOTP) that the device generates. In either case, the user gets back temporary security credentials that the user can then use to make additional requests to AWS.
**Note**  
MFA protection for a service's API operations is available only if the service supports temporary security credentials. For a list of these services, see [ Using Temporary Security Credentials to Access AWS](https://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html).

If authorization fails, AWS returns an access denied error message (as it does for any unauthorized access). With MFA-protected API policies in place, AWS denies access to the API operations specified in the policies if the user attempts to call an API operation without valid MFA authentication. The operation is also denied if the time stamp of the request for the API operation is outside of the allowed range specified in the policy. The user must be reauthenticated with MFA by requesting new temporary security credentials with an MFA code and device serial number.

### IAM policies with MFA conditions


Policies with MFA conditions can be attached to the following:
+ An IAM user or group
+ A resource such as an Amazon S3 bucket, Amazon SQS queue, or Amazon SNS topic
+ The trust policy of an IAM role that can be assumed by a user

You can use an MFA condition in a policy to check the following properties:
+ Existence—To simply verify that the user did authenticate with MFA, check that the `aws:MultiFactorAuthPresent` key is `True` in a `Bool` condition. The key is only present when the user authenticates with short-term credentials. Long-term credentials, such as access keys, do not include this key.
+ Duration—If you want to grant access only within a specified time after MFA authentication, use a numeric condition type to compare the `aws:MultiFactorAuthAge` key's age to a value (such as 3600 seconds). Note that the `aws:MultiFactorAuthAge` key is not present if MFA was not used.

The following example shows the trust policy of an IAM role that includes an MFA condition to test for the existence of MFA authentication. With this policy, users from the AWS account specified in the `Principal` element (replace `ACCOUNT-B-ID` with a valid AWS account ID) can assume the role that this policy is attached to. However such users can only assume the role if the user is authenticated using MFA.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {"AWS": "ACCOUNT-B-ID"},
    "Action": "sts:AssumeRole",
    "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
  }
}
```

------

For more information on the condition types for MFA, see [AWS global condition context keys](reference_policies_condition-keys.md), [Numeric condition operators](reference_policies_elements_condition_operators.md#Conditions_Numeric), and [Condition operator to check existence of condition keys](reference_policies_elements_condition_operators.md#Conditions_Null). 

### Choosing between GetSessionToken and AssumeRole


AWS STS provides two API operations that let users pass MFA information: `GetSessionToken` and `AssumeRole`. The API operation that the user calls to get temporary security credentials depends on which of the following scenarios applies. 

**Use `GetSessionToken` for the following scenarios:**
+ Call API operations that access resources in the same AWS account as the IAM user who makes the request. Note that temporary credentials from a `GetSessionToken` request can access IAM and AWS STS API operations *only* if you include MFA information in the request for credentials. Because temporary credentials returned by `GetSessionToken` include MFA information, you can check for MFA in individual API operations made by the credentials. 
+ Access to resources that are protected with resource-based policies that include an MFA condition.

The purpose of the `GetSessionToken` operation is to authenticate the user using MFA. You cannot use policies to control authentication operations.

**Use `AssumeRole` for the following scenarios:**
+ Call API operations that access resources in the same or a different AWS account. The API calls can include any IAM or AWS STS API. Note that to protect access you enforce MFA at the time when the user assumes the role. The temporary credentials returned by `AssumeRole` do not include MFA information in the context, so you cannot check individual API operations for MFA. This is why you must use `GetSessionToken` to restrict access to resources protected by resource-based policies.

**Note**  
AWS CloudTrail logs will contain MFA information when the IAM user sign in with MFA. If the IAM user assumes an IAM role, CloudTrail will also log `mfaAuthenticated: true` in the `sessionContext` attributes for actions performed using the assumed role. However, CloudTrail logging is separate from what IAM requires when API calls are made with the assumed role's credentials. For more information, see [CloudTrail userIdentity Element](https://docs.aws.amazon.com//awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html).

Details about how to implement these scenarios are provided later in this document.

### Important points about MFA-protected API access


It's important to understand the following aspects of MFA protection for API operations:
+ MFA protection is available only with temporary security credentials, which must be obtained with `AssumeRole` or `GetSessionToken`. 
+ You cannot use MFA-protected API access with AWS account root user credentials.
+ You cannot use MFA-protected API access with U2F security keys.
+ Federated users cannot be assigned an MFA device for use with AWS services, so they cannot access AWS resources controlled by MFA. (See next point.) 
+ Other AWS STS API operations that return temporary credentials do not support MFA. For `AssumeRoleWithWebIdentity` and `AssumeRoleWithSAML`, the user is authenticated by an external provider and AWS cannot determine whether that provider required MFA. For `GetFederationToken`, MFA is not necessarily associated with a specific user. 
+ Similarly, long-term credentials (IAM user access keys and root user access keys) cannot be used with MFA-protected API access because they don't expire.
+ `AssumeRole` and `GetSessionToken` can also be called without MFA information. In that case, the caller gets back temporary security credentials, but the session information for those temporary credentials does not indicate that the user authenticated with MFA.
+ To establish MFA protection for API operations, you add MFA conditions to policies. A policy must include the `aws:MultiFactorAuthPresent` condition key to enforce the use of MFA. For cross-account delegation, the role's trust policy must include the condition key.
+ When you allow another AWS account to access resources in your account, the security of your resources depends on the configuration of the trusted account (the other account, not yours). This is true even when you require multi-factor authentication. Any identity in the trusted account that has permission to create virtual MFA devices can construct an MFA claim to satisfy that part of your role's trust policy. Before you allow members of another account access to your AWS resources that require multi-factor authentication, you should ensure that the trusted account's owner follows security best practices. For example, the trusted account should restrict access to sensitive API operations, such as MFA device-management API operations, to specific, trusted identities.
+ If a policy includes an MFA condition, a request is denied if users have not been MFA authenticated, or if they provide an invalid MFA device identifier or invalid TOTP.

## Scenario: MFA protection for cross-account delegation


In this scenario, you want to delegate access to IAM users in another account, but only if the users are authenticated with an AWS MFA device. For more information about cross-account delegation, see [Roles terms and concepts](id_roles.md#id_roles_terms-and-concepts). 

Imagine that you have account A (the trusting account that owns the resource to be accessed), with the IAM user Anaya, who has administrator permission. She wants to grant access to user Richard in account B (the trusted account), but wants to make sure that Richard is authenticated with MFA before he assumes the role. 

1. In the trusting account A, Anaya creates an IAM role named `CrossAccountRole` and sets the principal in the role's trust policy to the account ID of account B. The trust policy grants permission to the AWS STS `AssumeRole` action. Anaya also adds an MFA condition to the trust policy, as in the following example. 

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": {
       "Effect": "Allow",
       "Principal": {"AWS": "ACCOUNT-B-ID"},
       "Action": "sts:AssumeRole",
       "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
     }
   }
   ```

------

1. Anaya adds a permissions policy to the role that specifies what the role is allowed to do. The permissions policy for a role with MFA protection is no different than any other role-permission policy. The following example shows the policy that Anaya adds to the role; it allows an assuming user to perform any Amazon DynamoDB action on the table `Books` in account A. This policy also allows the `dynamodb:ListTables` action, which is required to perform actions in the console. 
**Note**  
The permissions policy does not include an MFA condition. It is important to understand that the MFA authentication is used only to determine whether a user can assume the role. Once the user has assumed the role, no further MFA checks are made. 

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "TableActions",
               "Effect": "Allow",
               "Action": "dynamodb:*",
               "Resource": "arn:aws:dynamodb:*:111122223333:table/Books"
           },
           {
               "Sid": "ListTables",
               "Effect": "Allow",
               "Action": "dynamodb:ListTables",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. In trusted account B, the administrator makes sure that IAM user Richard is configured with an AWS MFA device and that he knows the ID of the device. The device ID is the serial number if it's a hardware MFA device, or the device's ARN if it's a virtual MFA device.

1. In account B, the administrator attaches the following policy to user Richard (or a group that he's a member of) that allows him to call the `AssumeRole` action. The resource is set to the ARN of the role that Anaya created in step 1. Notice that this policy does not contain an MFA condition.

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

****  

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

------

1. In account B, Richard (or an application that Richard is running) calls `AssumeRole`. The API call includes the ARN of the role to assume (`arn:aws:iam::ACCOUNT-A-ID:role/CrossAccountRole`), the ID of the MFA device, and the current TOTP that Richard gets from his device. 

   When Richard calls `AssumeRole`, AWS determines whether he has valid credentials, including the requirement for MFA. If so, Richard successfully assumes the role and can perform any DynamoDB action on the table named `Books` in account A while using the role's temporary credentials. 

   For an example of a program that calls `AssumeRole`, see [Calling AssumeRole with MFA authentication](id_credentials_mfa_sample-code.md#MFAProtectedAPI-example-assumerole).

## Scenario: MFA protection for access to API operations in the current account


In this scenario, you should ensure that a user in your AWS account can access sensitive API operations only when the user is authenticated using an AWS MFA device.

Imagine that you have account A that contains a group of developers who need to work with EC2 instances. Ordinary developers can work with the instances, but they are not granted permissions for the `ec2:StopInstances` or `ec2:TerminateInstances` actions. You want to limit those "destructive" privileged actions to just a few trusted users, so you add MFA protection to the policy that allows these sensitive Amazon EC2 actions. 

In this scenario, one of those trusted users is user Sofía. User Anaya is an administrator in account A. 

1. Anaya makes sure that Sofía is configured with an AWS MFA device and that Sofía knows the ID of the device. The device ID is the serial number if it's a hardware MFA device, or the device's ARN if it's a virtual MFA device. 

1. Anaya creates a group named `EC2-Admins` and adds user Sofía to the group.

1. Anaya attaches the following policy to the `EC2-Admins` group. This policy grants users permission to call the Amazon EC2 `StopInstances` and `TerminateInstances` actions only if the user has authenticated using MFA. 

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [{
       "Effect": "Allow",
       "Action": [
         "ec2:StopInstances",
         "ec2:TerminateInstances"
       ],
       "Resource": ["*"],
       "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
     }]
   }
   ```

------

1. 
**Note**  
For this policy to take effect, users must first sign out and then sign in again.

   If user Sofía needs to stop or terminate an Amazon EC2 instance, she (or an application that she is running) calls `GetSessionToken`. This API operation passes the ID of the MFA device and the current TOTP that Sofía gets from her device.

1. User Sofía (or an application that Sofía is using) uses the temporary credentials provided by `GetSessionToken` to call the Amazon EC2 `StopInstances` or `TerminateInstances` action. 

   For an example of a program that calls `GetSessionToken`, see [Calling GetSessionToken with MFA authentication](id_credentials_mfa_sample-code.md#MFAProtectedAPI-example-getsessiontoken) later in this document.

## Scenario: MFA protection for resources that have resource-based policies


In this scenario, you are the owner of an S3 bucket, an SQS queue, or an SNS topic. You want to make sure that any user from any AWS account who accesses the resource is authenticated by an AWS MFA device. 

This scenario illustrates a way to provide cross-account MFA protection without requiring users to assume a role first. In this case, the user can access the resource if three conditions are met: The user must be authenticated by MFA, be able to get temporary security credentials from `GetSessionToken`, and be in an account that is trusted by the resource's policy. 

Imagine that you are in account A and you create an S3 bucket. You want to grant access to this bucket to users who are in several different AWS accounts, but only if those users are authenticated with MFA.

In this scenario, user Anaya is an administrator in account A. User Nikhil is an IAM user in account C.

1. In account A, Anaya creates a bucket named `Account-A-bucket`.

1. Anaya adds the bucket policy to the bucket. The policy allows any user in account A, account B, or account C to perform the Amazon S3 `PutObject` and `DeleteObject` actions in the bucket. The policy includes an MFA condition. 

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [{
       "Effect": "Allow",
       "Principal": {"AWS": [
         "ACCOUNT-A-ID",
         "ACCOUNT-B-ID",
         "ACCOUNT-C-ID"
       ]},
       "Action": [
         "s3:PutObject",
         "s3:DeleteObject"
       ],
       "Resource": ["arn:aws:s3:::ACCOUNT-A-BUCKET-NAME/*"],
       "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
     }]
   }
   ```

------
**Note**  
Amazon S3 offers an MFA Delete feature for *root* account access (only). You can enable Amazon S3 MFA Delete when you set the versioning state of the bucket. Amazon S3 MFA Delete cannot be applied to an IAM user, and is managed independently from MFA-protected API access. An IAM user with permissions to delete a bucket cannot delete a bucket with Amazon S3 MFA Delete enabled. For more information on Amazon S3 MFA Delete, see [MFA Delete](https://docs.aws.amazon.com/AmazonS3/latest/dev/MultiFactorAuthenticationDelete.html).

1. In account C, an administrator makes sure that user Nikhil is configured with an AWS MFA device and that he knows the ID of the device. The device ID is the serial number if it's a hardware MFA device, or the device's ARN if it's a virtual MFA device. 

1. In account C, Nikhil (or an application that he is running) calls `GetSessionToken`. The call includes the ID or ARN of the MFA device and the current TOTP that Nikhil gets from his device. 

1. Nikhil (or an application that he is using) uses the temporary credentials returned by `GetSessionToken` to call the Amazon S3 `PutObject` action to upload a file to `Account-A-bucket`. 

   For an example of a program that calls `GetSessionToken`, see [Calling GetSessionToken with MFA authentication](id_credentials_mfa_sample-code.md#MFAProtectedAPI-example-getsessiontoken) later in this document.
**Note**  
The temporary credentials that `AssumeRole` returns won't work in this case. Although the user can provide MFA information to assume a role, the temporary credentials returned by `AssumeRole` don't include the MFA information. That information is required in order to meet the MFA condition in the policy. 

# Sample code: Requesting credentials with multi-factor authentication
Sample code: MFA

The following examples show how to call `GetSessionToken` and `AssumeRole` operations and pass MFA authentication parameters. No permissions are required to call `GetSessionToken`, but you must have a policy that allows you to call `AssumeRole`. The credentials returned are then used to list all S3 buckets in the account.

## Calling GetSessionToken with MFA authentication


The following example shows how to call `GetSessionToken` and pass MFA authentication information. The temporary security credentials returned by the `GetSessionToken` operation are then used to list all S3 buckets in the account.

The policy attached to the user who runs this code (or to a group that the user is in) provides the permissions for the returned temporary credentials. For this example code, the policy must grant the user permission to request the Amazon S3 `ListBuckets` operation. 

The following code examples show how to use `GetSessionToken`.

------
#### [ CLI ]

**AWS CLI**  
**To get a set of short term credentials for an IAM identity**  
The following `get-session-token` command retrieves a set of short-term credentials for the IAM identity making the call. The resulting credentials can be used for requests where multi-factor authentication (MFA) is required by policy. The credentials expire 15 minutes after they are generated.  

```
aws sts get-session-token \
    --duration-seconds 900 \
    --serial-number "YourMFADeviceSerialNumber" \
    --token-code 123456
```
Output:  

```
{
    "Credentials": {
        "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
        "Expiration": "2020-05-19T18:06:10+00:00"
    }
}
```
For more information, see [Requesting Temporary Security Credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) in the *AWS IAM User Guide*.  
+  For API details, see [GetSessionToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-session-token.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for a set period of time. The credentials used to request temporary credentials are inferred from the current shell defaults. To specify other credentials, use the -ProfileName or -AccessKey/-SecretKey parameters.**  

```
Get-STSSessionToken
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**Example 2: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for one hour. The credentials used to make the request are obtained from the specified profile.**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**Example 3: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for one hour using the identification number of the MFA device associated with the account whose credentials are specified in the profile 'myprofilename' and the value provided by the device.**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  For API details, see [GetSessionToken](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for a set period of time. The credentials used to request temporary credentials are inferred from the current shell defaults. To specify other credentials, use the -ProfileName or -AccessKey/-SecretKey parameters.**  

```
Get-STSSessionToken
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**Example 2: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for one hour. The credentials used to make the request are obtained from the specified profile.**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**Example 3: Returns an `Amazon.RuntimeAWSCredentials` instance containing temporary credentials valid for one hour using the identification number of the MFA device associated with the account whose credentials are specified in the profile 'myprofilename' and the value provided by the device.**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**Output:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  For API details, see [GetSessionToken](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------
#### [ Python ]

**SDK for Python (Boto3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples). 
Get a session token by passing an MFA token and use it to list Amazon S3 buckets for the account.  

```
def list_buckets_with_session_token_with_mfa(mfa_serial_number, mfa_totp, sts_client):
    """
    Gets a session token with MFA credentials and uses the temporary session
    credentials to list Amazon S3 buckets.

    Requires an MFA device serial number and token.

    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an Amazon Resource Name (ARN).
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    if mfa_serial_number is not None:
        response = sts_client.get_session_token(
            SerialNumber=mfa_serial_number, TokenCode=mfa_totp
        )
    else:
        response = sts_client.get_session_token()
    temp_credentials = response["Credentials"]

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Buckets for the account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
+  For API details, see [GetSessionToken](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/GetSessionToken) in *AWS SDK for Python (Boto3) API Reference*. 

------

## Calling AssumeRole with MFA authentication


The following examples show how to call `AssumeRole` and pass MFA authentication information. The temporary security credentials returned by `AssumeRole` are then used to list all Amazon S3 buckets in the account.

For more information about this scenario, see [Scenario: MFA protection for cross-account delegation](id_credentials_mfa_configure-api-require.md#MFAProtectedAPI-cross-account-delegation). 

The following code examples show how to use `AssumeRole`.

------
#### [ .NET ]

**SDK for .NET**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/STS#code-examples). 

```
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;

namespace AssumeRoleExample
{
    class AssumeRole
    {
        /// <summary>
        /// This example shows how to use the AWS Security Token
        /// Service (AWS STS) to assume an IAM role.
        ///
        /// NOTE: It is important that the role that will be assumed has a
        /// trust relationship with the account that will assume the role.
        ///
        /// Before you run the example, you need to create the role you want to
        /// assume and have it trust the IAM account that will assume that role.
        ///
        /// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
        /// for help in working with roles.
        /// </summary>

        // A region property may be used if the profile or credentials loaded do not specify a region,
        // or to use a specific region.
        private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2;

        static async Task Main()
        {
            // Create the SecurityToken client and then display the identity of the
            // default user.
            var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";

            var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);

            // Get and display the information about the identity of the default user.
            var callerIdRequest = new GetCallerIdentityRequest();
            var caller = await client.GetCallerIdentityAsync(callerIdRequest);
            Console.WriteLine($"Original Caller: {caller.Arn}");

            // Create the request to use with the AssumeRoleAsync call.
            var assumeRoleReq = new AssumeRoleRequest()
            {
                DurationSeconds = 1600,
                RoleSessionName = "Session1",
                RoleArn = roleArnToAssume
            };

            var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);

            // Now create a new client based on the credentials of the caller assuming the role.
            var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials, REGION);

            // Get and display information about the caller that has assumed the defined role.
            var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest);
            Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
        }
    }
}
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/sts-2011-06-15/AssumeRole) in *AWS SDK for .NET API Reference*. 

------
#### [ Bash ]

**AWS CLI with Bash script**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples). 

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function sts_assume_role
#
# This function assumes a role in the AWS account and returns the temporary
#  credentials.
#
# Parameters:
#       -n role_session_name -- The name of the session.
#       -r role_arn -- The ARN of the role to assume.
#
# Returns:
#       [access_key_id, secret_access_key, session_token]
#     And:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function sts_assume_role() {
  local role_session_name role_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function sts_assume_role"
    echo "Assumes a role in the AWS account and returns the temporary credentials:"
    echo "  -n role_session_name -- The name of the session."
    echo "  -r role_arn -- The ARN of the role to assume."
    echo ""
  }

  while getopts n:r:h option; do
    case "${option}" in
      n) role_session_name=${OPTARG} ;;
      r) role_arn=${OPTARG} ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done

  response=$(aws sts assume-role \
    --role-session-name "$role_session_name" \
    --role-arn "$role_arn" \
    --output text \
    --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-role operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/aws-cli/sts-2011-06-15/AssumeRole) in *AWS CLI Command Reference*. 

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sts#code-examples). 

```
bool AwsDoc::STS::assumeRole(const Aws::String &roleArn,
                             const Aws::String &roleSessionName,
                             const Aws::String &externalId,
                             Aws::Auth::AWSCredentials &credentials,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::STS::STSClient sts(clientConfig);
    Aws::STS::Model::AssumeRoleRequest sts_req;

    sts_req.SetRoleArn(roleArn);
    sts_req.SetRoleSessionName(roleSessionName);
    sts_req.SetExternalId(externalId);

    const Aws::STS::Model::AssumeRoleOutcome outcome = sts.AssumeRole(sts_req);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error assuming IAM role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Credentials successfully retrieved." << std::endl;
        const Aws::STS::Model::AssumeRoleResult result = outcome.GetResult();
        const Aws::STS::Model::Credentials &temp_credentials = result.GetCredentials();

        // Store temporary credentials in return argument.
        // Note: The credentials object returned by assumeRole differs
        // from the AWSCredentials object used in most situations.
        credentials.SetAWSAccessKeyId(temp_credentials.GetAccessKeyId());
        credentials.SetAWSSecretKey(temp_credentials.GetSecretAccessKey());
        credentials.SetSessionToken(temp_credentials.GetSessionToken());
    }

    return outcome.IsSuccess();
}
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/SdkForCpp/sts-2011-06-15/AssumeRole) in *AWS SDK for C\$1\$1 API Reference*. 

------
#### [ CLI ]

**AWS CLI**  
**To assume a role**  
The following `assume-role` command retrieves a set of short-term credentials for the IAM role `s3-access-example`.  

```
aws sts assume-role \
    --role-arn arn:aws:iam::123456789012:role/xaccounts3access \
    --role-session-name s3-access-example
```
Output:  

```
{
    "AssumedRoleUser": {
        "AssumedRoleId": "AROA3XFRBF535PLBIFPI4:s3-access-example",
        "Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"
    },
    "Credentials": {
        "SecretAccessKey": "9drTJvcXLB89EXAMPLELB8923FB892xMFI",
        "SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
        "Expiration": "2016-03-15T00:05:07Z",
        "AccessKeyId": "ASIAJEXAMPLEXEG2JICEA"
    }
}
```
The output of the command contains an access key, secret key, and session token that you can use to authenticate to AWS.  
For AWS CLI use, you can set up a named profile associated with a role. When you use the profile, the AWS CLI will call assume-role and manage credentials for you. For more information, see [Use an IAM role in the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html) in the *AWS CLI User Guide*.  
+  For API details, see [AssumeRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html) in *AWS CLI Command Reference*. 

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

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sts#code-examples). 

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

/**
 * To make this code example work, create a Role that you want to assume.
 * Then define a Trust Relationship in the AWS Console. You can use this as an
 * example:
 *
 * {
 * "Version":"2012-10-17",		 	 	 
 * "Statement": [
 * {
 * "Effect": "Allow",
 * "Principal": {
 * "AWS": "<Specify the ARN of your IAM user you are using in this code example>"
 * },
 * "Action": "sts:AssumeRole"
 * }
 * ]
 * }
 *
 * For more information, see "Editing the Trust Relationship for an Existing
 * Role" in the AWS Directory Service guide.
 *
 * Also, set up your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class AssumeRole {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleArn> <roleSessionName>\s

                Where:
                    roleArn - The Amazon Resource Name (ARN) of the role to assume (for example, arn:aws:iam::000008047983:role/s3role).\s
                    roleSessionName - An identifier for the assumed role session (for example, mysession).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleArn = args[0];
        String roleSessionName = args[1];
        Region region = Region.US_EAST_1;
        StsClient stsClient = StsClient.builder()
                .region(region)
                .build();

        assumeGivenRole(stsClient, roleArn, roleSessionName);
        stsClient.close();
    }

    public static void assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();

            // Display the time when the temp creds expire.
            Instant exTime = myCreds.expiration();
            String tokenInfo = myCreds.sessionToken();

            // Convert the Instant to readable date.
            DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                    .withLocale(Locale.US)
                    .withZone(ZoneId.systemDefault());

            formatter.format(exTime);
            System.out.println("The token " + tokenInfo + "  expires on " + exTime);

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/sts-2011-06-15/AssumeRole) in *AWS SDK for Java 2.x API Reference*. 

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

**SDK for JavaScript (v3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sts#code-examples). 
Create the client.  

```
import { STSClient } from "@aws-sdk/client-sts";
// Set the AWS Region.
const REGION = "us-east-1";
// Create an AWS STS service client object.
export const client = new STSClient({ region: REGION });
```
Assume the IAM role.  

```
import { AssumeRoleCommand } from "@aws-sdk/client-sts";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Returns a set of temporary security credentials that you can use to
    // access Amazon Web Services resources that you might not normally
    // have access to.
    const command = new AssumeRoleCommand({
      // The Amazon Resource Name (ARN) of the role to assume.
      RoleArn: "ROLE_ARN",
      // An identifier for the assumed role session.
      RoleSessionName: "session1",
      // The duration, in seconds, of the role session. The value specified
      // can range from 900 seconds (15 minutes) up to the maximum session
      // duration set for the role.
      DurationSeconds: 900,
    });
    const response = await client.send(command);
    console.log(response);
  } catch (err) {
    console.error(err);
  }
};
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sts/command/AssumeRoleCommand) in *AWS SDK for JavaScript API Reference*. 

**SDK for JavaScript (v2)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sts#code-examples). 

```
// Load the AWS SDK for Node.js
const AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

var roleToAssume = {
  RoleArn: "arn:aws:iam::123456789012:role/RoleName",
  RoleSessionName: "session1",
  DurationSeconds: 900,
};
var roleCreds;

// Create the STS service object
var sts = new AWS.STS({ apiVersion: "2011-06-15" });

//Assume Role
sts.assumeRole(roleToAssume, function (err, data) {
  if (err) console.log(err, err.stack);
  else {
    roleCreds = {
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken,
    };
    stsGetCallerIdentity(roleCreds);
  }
});

//Get Arn of current identity
function stsGetCallerIdentity(creds) {
  var stsParams = { credentials: creds };
  // Create STS service object
  var sts = new AWS.STS(stsParams);

  sts.getCallerIdentity({}, function (err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {
      console.log(data.Arn);
    }
  });
}
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sts-2011-06-15/AssumeRole) in *AWS SDK for JavaScript API Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Returns a set of temporary credentials (access key, secret key and session token) that can be used for one hour to access AWS resources that the requesting user might not normally have access to. The returned credentials have the permissions that are allowed by the access policy of the role being assumed and the policy that was supplied (you cannot use the supplied policy to grant permissions in excess of those defined by the access policy of the role being assumed).**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**Example 2: Returns a set of temporary credentials, valid for one hour, that have the same permissions that are defined in the access policy of the role being assumed.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**Example 3: Returns a set of temporary credentials supplying the serial number and generated token from an MFA associated with the user credentials used to execute the cmdlet.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**Example 4: Returns a set of temporary credentials that have assumed a role defined in a customer account. For each role that the third party can assume, the customer account must create a role using an identifier that must be passed in the -ExternalId parameter each time the role is assumed.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Returns a set of temporary credentials (access key, secret key and session token) that can be used for one hour to access AWS resources that the requesting user might not normally have access to. The returned credentials have the permissions that are allowed by the access policy of the role being assumed and the policy that was supplied (you cannot use the supplied policy to grant permissions in excess of those defined by the access policy of the role being assumed).**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**Example 2: Returns a set of temporary credentials, valid for one hour, that have the same permissions that are defined in the access policy of the role being assumed.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**Example 3: Returns a set of temporary credentials supplying the serial number and generated token from an MFA associated with the user credentials used to execute the cmdlet.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**Example 4: Returns a set of temporary credentials that have assumed a role defined in a customer account. For each role that the third party can assume, the customer account must create a role using an identifier that must be passed in the -ExternalId parameter each time the role is assumed.**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------
#### [ Python ]

**SDK for Python (Boto3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples). 
Assume an IAM role that requires an MFA token and use temporary credentials to list Amazon S3 buckets for the account.  

```
def list_buckets_from_assumed_role_with_mfa(
    assume_role_arn, session_name, mfa_serial_number, mfa_totp, sts_client
):
    """
    Assumes a role from another account and uses the temporary credentials from
    that role to list the Amazon S3 buckets that are owned by the other account.
    Requires an MFA device serial number and token.

    The assumed role must grant permission to list the buckets in the other account.

    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an ARN.
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    response = sts_client.assume_role(
        RoleArn=assume_role_arn,
        RoleSessionName=session_name,
        SerialNumber=mfa_serial_number,
        TokenCode=mfa_totp,
    )
    temp_credentials = response["Credentials"]
    print(f"Assumed role {assume_role_arn} and got temporary credentials.")

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Listing buckets for the assumed role's account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole) in *AWS SDK for Python (Boto3) API Reference*. 

------
#### [ Ruby ]

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples). 

```
  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end
```
+  For API details, see [AssumeRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/sts-2011-06-15/AssumeRole) in *AWS SDK for Ruby API Reference*. 

------
#### [ Rust ]

**SDK for Rust**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sts/#code-examples). 

```
async fn assume_role(config: &SdkConfig, role_name: String, session_name: Option<String>) {
    let provider = aws_config::sts::AssumeRoleProvider::builder(role_name)
        .session_name(session_name.unwrap_or("rust_sdk_example_session".into()))
        .configure(config)
        .build()
        .await;

    let local_config = aws_config::from_env()
        .credentials_provider(provider)
        .load()
        .await;
    let client = Client::new(&local_config);
    let req = client.get_caller_identity();
    let resp = req.send().await;
    match resp {
        Ok(e) => {
            println!("UserID :               {}", e.user_id().unwrap_or_default());
            println!("Account:               {}", e.account().unwrap_or_default());
            println!("Arn    :               {}", e.arn().unwrap_or_default());
        }
        Err(e) => println!("{:?}", e),
    }
}
```
+  For API details, see [AssumeRole](https://docs.rs/aws-sdk-sts/latest/aws_sdk_sts/client/struct.Client.html#method.assume_role) in *AWS SDK for Rust API reference*. 

------
#### [ Swift ]

**SDK for Swift**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples). 

```
import AWSSTS

    public func assumeRole(role: IAMClientTypes.Role, sessionName: String)
        async throws -> STSClientTypes.Credentials
    {
        let input = AssumeRoleInput(
            roleArn: role.arn,
            roleSessionName: sessionName
        )
        do {
            let output = try await stsClient.assumeRole(input: input)

            guard let credentials = output.credentials else {
                throw ServiceHandlerError.authError
            }

            return credentials
        } catch {
            print("Error assuming role: ", dump(error))
            throw error
        }
    }
```
+  For API details, see [AssumeRole](https://sdk.amazonaws.com/swift/api/awssts/latest/documentation/awssts/stsclient/assumerole(input:)) in *AWS SDK for Swift API reference*. 

------

# Service-specific credentials for IAM users
Service-specific credentials

Service-specific credentials are specialized authentication mechanisms designed for specific AWS services. These credentials provide simplified authentication compared to standard AWS credentials, and are tailored to the authentication requirements of individual AWS services. Unlike access keys, which can be used across multiple AWS services, service-specific credentials are designed for use with only the service for which they were created. This targeted approach enhances security by limiting the scope of the credentials.

Service-specific credentials typically consist of a user name and password pair or specialized API keys that are formatted according to the requirements of the specific service. When you create service-specific credentials, they are active by default and can be used immediately. You can have a maximum of two sets of service-specific credentials for each supported service per IAM user. This limit allows you to maintain one active set while rotating to a new set when needed. AWS currently supports service-specific credentials for the following services:

## When to use service-specific credentials


Service-specific credentials are intended for compatibility with third-party libraries, SDKs, tools, or applications that are not natively compatible with AWS credentials, AWS SDKs, or AWS APIs. Such use cases include migrating to AWS services from self-hosted infrastructure or from services hosted by other providers.

When starting from scratch, and wherever possible, we recommend that you use AWS temporary credentials, such as those provided by an IAM role, to authenticate with an AWS service using an AWS SDK or a library that supports AWS temporary credentials.

## Rotating service-specific credentials


As a security best practice, rotate service-specific credentials regularly. To rotate credentials without disrupting your applications:

1. Create a second set of service-specific credentials for the same service and IAM user

1. Update all applications to use the new credentials and verify they work correctly

1. Change the status of the original credentials to "Inactive"

1. Verify that all applications are still functioning properly

1. Delete the inactive service-specific credentials when you're confident they're no longer needed

## Monitoring service-specific credentials


You can use AWS CloudTrail to monitor the use of service-specific credentials in your AWS account. To view CloudTrail events related to service-specific credential usage, review the CloudTrail logs for events from the service where the credentials are used. For more information, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md).

For additional security, consider setting up CloudWatch alarms to notify you of specific credential usage patterns that might indicate unauthorized access or other security concerns. For more information, see [Monitoring CloudTrail Log Files with Amazon CloudWatch Logs](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html) in the *AWS CloudTrail User Guide*.

The following topics provide information about service-specific credentials.

**Topics**
+ [

## When to use service-specific credentials
](#id_credentials_service-specific-creds-usecase)
+ [

## Rotating service-specific credentials
](#id_credentials_service-specific-creds-rotation)
+ [

## Monitoring service-specific credentials
](#id_credentials_service-specific-creds-monitoring)
+ [

# API keys for AWS services
](id_credentials_api_keys_for_aws_services.md)
+ [

# Use IAM with Amazon Keyspaces (for Apache Cassandra)
](id_credentials_keyspaces.md)

# API keys for AWS services
API keys for AWS services

You can access AWS services through the AWS Management Console and programmatically using the AWS CLI or AWS API. When making programmatic requests to services like Amazon Bedrock and Amazon CloudWatch Logs, you can authenticate using IAM credentials (for example, temporary security credentials or long-term access keys) or API keys. There are two types of API keys:
+ **Long-term API keys** – Long-term API keys are associated with an IAM user and generated using IAM [service-specific credentials](id_credentials_service-specific-creds.md). These credentials are designed for use with only a single AWS service, enhancing security by limiting credential scope. You can set an expiration time for the long-term API key. You can use the IAM or service-specific console (for example, Amazon Bedrock or CloudWatch Logs console), the AWS CLI, or AWS API to generate long-term API keys.
+ **Short-term API keys** (only supported by Amazon Bedrock) – A short-term API key is a pre-signed URL that uses AWS Signature Version 4. Short-term API keys share the same permissions and expiration as the credentials of the identity that generates the API key and are valid for up to 12 hours or the remaining time of your console session, whichever is shorter. You can use the Amazon Bedrock console, Python package `aws-bedrock-token-generator`, and packages for other programming languages to generate short-term API keys. For more information, see [Generate Amazon Bedrock API keys for easy access to the Amazon Bedrock API](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html) in the *Amazon Bedrock User Guide*.

**Note**  
Long-term API keys have a higher security risk compared to short-term API keys. We recommend using short-term API keys or temporary security credentials when possible. If you use long-term API keys, we recommend implementing regular key rotation practices.

## Supported services


The following table lists the AWS services that support API keys and the type of API key each service supports.


| \$1 | Service | Long-term API keys | Short-term API keys | Managed policy auto-attached | 
| --- | --- | --- | --- | --- | 
| 1 | Amazon Bedrock | Yes | Yes | [AmazonBedrockLimitedAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonBedrockLimitedAccess.html) | 
| 2 | Amazon CloudWatch Logs | Yes | N/A | [CloudWatchLogsAPIKeyAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/CloudWatchLogsAPIKeyAccess.html) | 

When you generate a long-term API key for a service, the corresponding AWS managed policy is automatically attached to the IAM user, granting access to core operations for that service. If you require additional access, you can modify the permissions for the IAM user. For information about modifying permissions, see [Adding and removing IAM identity permissions](access_policies_manage-attach-detach.md). For more information on how to use an Amazon Bedrock key, see [Use an Amazon Bedrock API key](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-use.html) in the *Amazon Bedrock User Guide*. For more information on how to use bearer token for Amazon CloudWatch Logs, see [Bearer token authentication](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_HTTP_Endpoints_BearerTokenAuth.html) in the *CloudWatch Logs User Guide*.

## Prerequisites for long-term API keys


Before you can generate a long-term API key in the IAM console, you must meet these prerequisites:
+ An IAM user to associate with the long-term API key. For instructions on creating an IAM user, see [Create an IAM user in your AWS account](id_users_create.md).
+ You must have the following IAM policy permissions to manage service-specific credentials for an IAM user. The example policy grants permission to create, list, update, delete, and reset service-specific credentials. Replace the `username` value in the Resource element with the name of the IAM user you will generate long-term API keys for:

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "ManageBedrockServiceSpecificCredentials",
              "Effect": "Allow",
              "Action": [
                  "iam:CreateServiceSpecificCredential",
                  "iam:ListServiceSpecificCredentials",
                  "iam:UpdateServiceSpecificCredential",
                  "iam:DeleteServiceSpecificCredential",
                  "iam:ResetServiceSpecificCredential"
              ],
              "Resource": "arn:aws:iam::*:user/username"
          }
      ]
  }
  ```

------

## Generating a long-term API key (console)


**To generate a long-term API key for a specific service in the IAM console**

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, choose **Users**.

1. Choose the IAM user you want to generate a long-term API key for.

1. Choose the **Security credentials** tab.

1. In the **API keys** section, choose **Generate API key**.

1. From the **AWS service** dropdown list, choose the service that you want the API key to authenticate to.

1. For **API key expiration**, do one of the following:
   + Choose an API key expiration duration of **1**, **5**, **30**, **90**, or **365** days.
   + Choose **Custom duration** to specify a custom API key expiration date.
   + Choose **Never expires** (not recommended).

1. Choose **Generate API key**.

1. Copy or download your API key. This is the only time you can view the API key value.
**Important**  
Store your API key securely. After you close the dialog box, you cannot retrieve the API key again. If you lose or forget your API key, you cannot retrieve it. Instead, generate a new API key and make the old key inactive.

## Generating a long-term API key (AWS CLI)


To generate a long-term API key using the AWS CLI, use the following steps:

1. Create an IAM user that will be used with Amazon Bedrock or Amazon CloudWatch Logs using the [ create-user](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-user.html) command:

   ```
   aws iam create-user \
       --user-name APIKeyUser_1
   ```

1. Attach the AWS managed policy to the IAM user using the [ attach-user-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-user-policy.html) command.

   For Amazon Bedrock:

   ```
   aws iam attach-user-policy --user-name APIKeyUser_1 \
       --policy-arn arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess
   ```

   For Amazon CloudWatch Logs:

   ```
   aws iam attach-user-policy --user-name APIKeyUser_1 \
       --policy-arn arn:aws:iam::aws:policy/CloudWatchLogsAPIKeyAccess
   ```

1. Generate the long-term API key using the [ create-service-specific-credential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-service-specific-credential.html) command.

   For Amazon Bedrock:

   ```
   aws iam create-service-specific-credential \
       --user-name APIKeyUser_1 \
       --service-name bedrock.amazonaws.com \
       --credential-age-days 30
   ```

   For Amazon CloudWatch Logs:

   ```
   aws iam create-service-specific-credential \
       --user-name APIKeyUser_1 \
       --service-name logs.amazonaws.com \
       --credential-age-days 30
   ```
**Note**  
The `--credential-age-days` parameter is optional. You can specify a value between 1–36600 days. If you omit this parameter, the API key does not expire.

The returned `ServiceApiKeyValue` in the response is your long-term API key for the respective service. Store the `ServiceApiKeyValue` value securely, as you cannot retrieve it later.

### List long-term API keys (AWS CLI)


To list long-term API keys metadata for a specific user, use the [ list-service-specific-credentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-service-specific-credentials.html) command with the `--user-name` parameter:

```
aws iam list-service-specific-credentials \
    --service-name bedrock.amazonaws.com \
    --user-name APIKeyUser_1
```

**Note**  
Replace `bedrock.amazonaws.com` with the appropriate service name (for example, `logs.amazonaws.com` for Amazon CloudWatch Logs).

To list all long-term API keys metadata in the account, use the [ list-service-specific-credentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-service-specific-credentials.html) command with the `--all-users` parameter:

```
aws iam list-service-specific-credentials \
    --service-name bedrock.amazonaws.com \
    --all-users
```

### Update long-term API key status (AWS CLI)


To update the status of a long-term API key, use the [ update-service-specific-credential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-service-specific-credential.html) command:

```
aws iam update-service-specific-credential \
    --user-name "APIKeyUser_1" \
    --service-specific-credential-id "ACCA1234EXAMPLE1234" \
    --status Inactive|Active
```

## Generating a long-term API key (AWS API)


You can use the following IAM API operations to manage long-term API keys for any supported service:
+  [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html) 
+  [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServiceSpecificCredentials.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServiceSpecificCredentials.html) 
+  [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html) 
+  [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html) 
+  [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html) 

## Short-term API keys (Amazon Bedrock)


Short-term API keys are currently supported by Amazon Bedrock only. For information on generating and using short-term API keys, see [Generate an API key](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-generate.html) in the *Amazon Bedrock User Guide*.

## Service-specific information

+ For more information about using API keys with Amazon Bedrock, see [Use an Amazon Bedrock API key](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-use.html) in the *Amazon Bedrock User Guide*.
+ For more information about using API keys with Amazon CloudWatch Logs, see [Log ingestion through HTTP endpoints](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_HTTP_Endpoints.html) in the *Amazon CloudWatch Logs User Guide*.

# Use IAM with Amazon Keyspaces (for Apache Cassandra)
Use IAM with Amazon Keyspaces

Amazon Keyspaces (for Apache Cassandra) is a scalable, highly available, and managed Apache Cassandra-compatible database service. You can access Amazon Keyspaces through the AWS Management Console, or programmatically. To access Amazon Keyspaces programmatically with service-specific credentials, you can use `cqlsh` or open-source Cassandra drivers. *Service-specific credentials* include a user name and password like those that Cassandra uses for authentication and access management. You can have a maximum of two sets of service-specific credentials for each supported service per user.

To access Amazon Keyspaces programmatically with AWS access keys, you can use the AWS SDK, the AWS Command Line Interface (AWS CLI) or open-source Cassandra drivers with the SigV4 plugin. To learn more, see [Create and configure AWS credentials for Amazon Keyspaces](https://docs.aws.amazon.com//keyspaces/latest/devguide/access.credentials.html) in the *Amazon Keyspaces (for Apache Cassandra) Developer Guide*.

**Note**  
If you plan to interact with Amazon Keyspaces only through the console, you don't need to generate service-specific credentials. For more information, see [Accessing Amazon Keyspaces using the console](https://docs.aws.amazon.com/keyspaces/latest/devguide/console_keyspaces.html) in the *Amazon Keyspaces (for Apache Cassandra) Developer Guide*.

For more information about the permissions required to access Amazon Keyspaces, see [Amazon Keyspaces (for Apache Cassandra) Identity-Based Policy Examples](https://docs.aws.amazon.com/keyspaces/latest/devguide/security_iam_id-based-policy-examples.html#security_iam_id-based-policy-examples-console) in the *Amazon Keyspaces (for Apache Cassandra) Developer Guide*.

## Generating Amazon Keyspaces credentials (console)


You can use the AWS Management Console to generate Amazon Keyspaces (for Apache Cassandra) credentials for your IAM users.

**To generate Amazon Keyspaces service-specific credentials (console)**

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, choose **Users** and then choose the name of the user that requires the credentials.

1. On the **Security Credentials** tab beneath **Credentials for Amazon Keyspaces (for Apache Cassandra)**, choose **Generate credentials**.

1. Your service-specific credentials are now available. This is the only time that the password can be viewed or downloaded. You cannot recover it later. However, you can reset your password at any time. Save the user and password in a secure location, because you'll need them later.

## Generating Amazon Keyspaces credentials (AWS CLI)


You can use the AWS CLI to generate Amazon Keyspaces (for Apache Cassandra) credentials for your IAM users.

**To generate Amazon Keyspaces service-specific credentials (AWS CLI)**
+ Use the following command:
  + [aws iam create-service-specific-credential](https://docs.aws.amazon.com/cli/latest/reference/iam/create-service-specific-credential.html)

## Generating Amazon Keyspaces credentials (AWS API)


You can use the AWS API to generate Amazon Keyspaces (for Apache Cassandra) credentials for your IAM users.

**To generate Amazon Keyspaces service-specific credentials (AWS API)**
+ Complete the following operation:
  + [CreateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html) 

# Find unused AWS credentials
Find unused credentials

To increase the security of your AWS account, remove IAM user credentials (that is, passwords and access keys) that are not needed. For example, when users leave your organization or no longer need AWS access, find the credentials that they were using and ensure that they are no longer operational. Ideally, you delete credentials if they are no longer needed. You can always recreate them at a later date if the need arises. At the very least, you should change the password or deactivate the access keys so that the former users no longer have access.

Of course, the definition of *unused* can vary and usually means a credential that has not been used within a specified period of time.

## Finding unused passwords


You can use the AWS Management Console to view password usage information for your users. If you have a large number of users, you can use the console to download a credential report with information about when each user last used their console password. You can also access the information from the AWS CLI or the IAM API.

**To find unused passwords (console)**

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, choose **Users**.

1. If necessary, add the **Console last sign-in** column to the users table:

   1. Above the table on the far right, choose the settings icon (![\[Settings icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)).

   1. In **Select visible columns**, select **Console last sign-in**.

   1. Choose **Confirm** to return to the list of users.

1. The **Console last sign-in** column shows the date when the user last signed in to AWS through the console. You can use this information to find users with passwords who have not signed in for more than a specified period of time. The column displays **Never** for users with passwords that have never signed in. **None** indicates users with no passwords. Passwords that have not been used recently might be good candidates for removal.
**Important**  
Due to a service issue, password last used data does not include password use from May 3rd 2018 22:50 PDT to May 23rd 2018 14:08 PDT. This affects [last sign-in](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html) dates shown in the IAM console and password last used dates in the [IAM credential report](https://docs.aws.amazon.com/IAM/latest/UserGuide/SupportedTypes.xmlid_credentials_getting-report.html), and returned by the [GetUser API operation](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html). If users signed in during the affected time, the password last used date that is returned is the date the user last signed in before May 3rd 2018. For users that signed in after May 23rd 2018 14:08 PDT, the returned password last used date is accurate.  
If you use password last used information to identify unused credentials for deletion, such as deleting users who did not sign in to AWS in the last 90 days, we recommend that you adjust your evaluation window to include dates after May 23rd 2018. Alternatively, if your users use access keys to access AWS programmatically you can refer to access key last used information because it is accurate for all dates. 

**To find unused passwords by downloading the credentials report (console)**

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, choose **Credential report**.

1. Choose **Download Report** to download a comma-separated value (CSV) file named `status_reports_<date>T<time>.csv`. The fifth column contains the `password_last_used` column with the dates or one of the following:
   + **N/A** – Users that do not have a password assigned at all.
   + **no\$1information** – Users that have not used their password since IAM began tracking password age on October 20, 2014.

**To find unused passwords (AWS CLI)**  
Run the following command to find unused passwords:
+ `[aws iam list-users](https://docs.aws.amazon.com/cli/latest/reference/iam/list-users.html)` returns a list of users, each with a `PasswordLastUsed` value. If the value is missing, then the user either has no password or the password has not been used since IAM began tracking password age on October 20, 2014.

**To find unused passwords (AWS API)**  
Call the following operation to find unused passwords:
+  ` [ListUsers](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUsers.html)` returns a collection of users, each of which has a `<PasswordLastUsed>` value. If the value is missing, then the user either has no password or the password has not been used since IAM began tracking password age on October 20, 2014.

For information about the commands to download the credentials report, see [Getting credential reports (AWS CLI)](id_credentials_getting-report.md#getting-credential-reports-cliapi).

## Finding unused access keys


You can use the AWS Management Console to view access key usage information for your users. If you have a large number of users, you can use the console to download a credentials report to find when each user last used their access keys. You can also access the information from the AWS CLI or the IAM API.

**To find unused access keys (console)**

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, choose **Users**.

1. If necessary, add the **Access key last used** column to the users table:

   1. Above the table on the far right, choose the settings icon (![\[Settings icon\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/console-settings-icon.console.png)).

   1. In **Select visible columns**, select **Access key last used**.

   1. Choose **Confirm** to return to the list of users.

1. The **Access key last used** column shows the number of days since the user last accessed AWS programmatically. You can use this information to find users with access keys that have not been used for more than a specified period of time. The column displays **–** for users with no access keys. Access keys that have not been used recently might be good candidates for removal.

**To find unused access keys by downloading the credentials report (console)**

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, choose **Credential Report**.

1. Choose **Download Report** to download a comma-separated value (CSV) file named `status_reports_<date>T<time>.csv`. Columns 11 through 13 contain the last used date, Region, and service information for access key 1. Columns 16 through 18 contain the same information for access key 2. The value is **N/A** if the user does not have an access key or the user has not used the access key since IAM began tracking access key age on April 22, 2015.

**To find unused access keys (AWS CLI)**  
Run the following commands to find unused access keys:
+ `[aws iam list-access-keys](https://docs.aws.amazon.com/cli/latest/reference/iam/list-access-keys.html)` returns information about the access keys for a user, including the `AccessKeyID`.
+ `[aws iam get-access-key-last-used](https://docs.aws.amazon.com/cli/latest/reference/iam/get-access-key-last-used.html)` takes an access key ID and returns output that includes the `LastUsedDate`, the `Region` in which the access key was last used, and the `ServiceName` of the last service requested. If `LastUsedDate` is missing, then the access key has not been used since IAM began tracking access key age on April 22, 2015.

**To find unused access keys (AWS API)**  
Call the following operations to find unused access keys:
+ `[ListAccessKeys](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html)` returns a list of `AccessKeyID` values for access keys that are associated with the specified user. 
+ `[GetAccessKeyLastUsed](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html)` takes an access key ID and returns a collection of values. Included are the `LastUsedDate`, the `Region` in which the access key was last used, and the `ServiceName` of the last service requested. If the value is missing, then either the user has no access key or the access key has not been used since IAM began tracking access key age on April 22, 2015.

For information about the commands to download the credentials report, see [Getting credential reports (AWS CLI)](id_credentials_getting-report.md#getting-credential-reports-cliapi).

# Generate credential reports for your AWS account
Generate credential reports

You can generate and download a *credential report* that lists all users in your account and the status of their various credentials, including passwords, access keys, and MFA devices. You can get a credential report from the AWS Management Console, the [AWS SDKs](https://aws.amazon.com/tools) and [Command Line Tools](https://aws.amazon.com/tools/#Command_Line_Tools), or the IAM API. 

**Note**  
The IAM credential report only includes the following IAM-managed credentials: passwords, the first two access keys per user, MFA devices, and X.509 signing certificates. The report does not include service-specific credentials (such as CodeCommit passwords, Amazon Bedrock long-term API keys, or Amazon CloudWatch Logs long-term API keys) or any other user access keys beyond the first two. For complete credential visibility, use the [ListServiceSpecificCredentials](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServiceSpecificCredentials.html) and [ListAccessKeys](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html) APIs.

You can use credential reports to assist in your auditing and compliance efforts. You can use the report to audit the effects of credential lifecycle requirements, such as password and access key updates. You can provide the report to an external auditor, or grant permissions to an auditor so that he or she can download the report directly.

You can generate a credential report as often as once every four hours. When you request a report, IAM first checks whether a report for the AWS account has been generated within the past four hours. If so, the most recent report is downloaded. If the most recent report for the account is older than four hours, or if there are no previous reports for the account, IAM generates and downloads a new report. 

**Topics**
+ [

## Required permissions
](#id_credentials_required_permissions)
+ [

## Understanding the report format
](#id_credentials_understanding_the_report_format)
+ [

## Getting credential reports (console)
](#getting-credential-reports-console)
+ [

## Getting credential reports (AWS CLI)
](#getting-credential-reports-cliapi)
+ [

## Getting credential reports (AWS API)
](#getting-credential-reports-api)

## Required permissions


The following permissions are needed to create and download reports:
+ To create a credential report: `iam:GenerateCredentialReport` 
+ To download the report: `iam:GetCredentialReport`

## Understanding the report format


Credential reports are formatted as comma-separated values (CSV) files. You can open CSV files with common spreadsheet software to perform analysis, or you can build an application that consumes the CSV files programmatically and performs custom analysis. 

The CSV file contains the following columns:

**user**  
The friendly name of the user. 

**arn**  
The Amazon Resource Name (ARN) of the user. For more information about ARNs, see [IAM ARNs](reference_identifiers.md#identifiers-arns). 

**user\$1creation\$1time**  
The date and time when the user was created, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601).

**password\$1enabled**  
When the user has a password, this value is `TRUE`. Otherwise it is `FALSE`. This value is `FALSE` for new member accounts created as part of your organization as they have no root user credentials by default.

**password\$1last\$1used**  
The date and time when the AWS account root user or user's password was last used to sign in to an AWS website, in [ISO 8601 date-time format](http://www.iso.org/iso/iso8601). AWS websites that capture a user's last sign-in time are the AWS Management Console, the AWS Discussion Forums, and the AWS Marketplace. When a password is used more than once in a 5-minute span, only the first use is recorded in this field.   
+ The value in this field is `no_information` in these cases:
  + The user's password has never been used.
  + There is no sign-in data associated with the password, such as when user's password has not been used after IAM started tracking this information on October 20, 2014.
+ The value in this field is `N/A` (not applicable) when the user does not have a password.

**Important**  
Due to a service issue, password last used data does not include password use from May 3rd 2018 22:50 PDT to May 23rd 2018 14:08 PDT. This affects [last sign-in](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html) dates shown in the IAM console and password last used dates in the [IAM credential report](https://docs.aws.amazon.com/IAM/latest/UserGuide/SupportedTypes.xmlid_credentials_getting-report.html), and returned by the [GetUser API operation](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html). If users signed in during the affected time, the password last used date that is returned is the date the user last signed in before May 3rd 2018. For users that signed in after May 23rd 2018 14:08 PDT, the returned password last used date is accurate.  
If you use password last used information to identify unused credentials for deletion, such as deleting users who did not sign in to AWS in the last 90 days, we recommend that you adjust your evaluation window to include dates after May 23rd 2018. Alternatively, if your users use access keys to access AWS programmatically you can refer to access key last used information because it is accurate for all dates. 

**password\$1last\$1changed**  
The date and time when the user's password was last set, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601). If the user does not have a password, the value in this field is `N/A` (not applicable).

**password\$1next\$1rotation**  
When the account has a [password policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html) that requires password rotation, this field contains the date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user is required to set a new password. The value for the AWS account (root) is always `not_supported`.

**mfa\$1active**  
When a [multi-factor authentication](id_credentials_mfa.md) (MFA) device has been enabled for the user, this value is `TRUE`. Otherwise it is `FALSE`.

**access\$1key\$11\$1active**  
When the user has an access key and the access key's status is `Active`, this value is `TRUE`. Otherwise it is `FALSE`. Applies to both account root user and IAM users.

**access\$1key\$11\$1last\$1rotated**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's access key was created or last changed. If the user does not have an active access key, the value in this field is `N/A` (not applicable). Applies to both account root user and IAM users.

**access\$1key\$11\$1last\$1used\$1date**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's access key was most recently used to sign an AWS API request. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users.  
The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have an access key.
+ The access key has never been used.
+ The access key has not been used after IAM started tracking this information on April 22, 2015.

**access\$1key\$11\$1last\$1used\$1region**  
The [AWS Region](https://docs.aws.amazon.com/general/latest/gr/rande.html) in which the access key was most recently used. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users.  
The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have an access key.
+ The access key has never been used.
+ The access key was last used before IAM started tracking this information on April 22, 2015.
+ The last used service is not Region-specific, such as Amazon S3.

**access\$1key\$11\$1last\$1used\$1service**  
The AWS service that was most recently accessed with the access key. The value in this field uses the service's namespace—for example, `s3` for Amazon S3 and `ec2` for Amazon EC2. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users.  
The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have an access key.
+ The access key has never been used.
+ The access key was last used before IAM started tracking this information on April 22, 2015.

**access\$1key\$12\$1active**  
When the user has a second access key and the second key's status is `Active`, this value is `TRUE`. Otherwise it is `FALSE`. Applies to both account root user and IAM users.  
Users can have up to two access keys, to make rotation easier by updating the key first and then deleting the previous key. For more information about updating access keys, see [Update access keys](id-credentials-access-keys-update.md).

**access\$1key\$12\$1last\$1rotated**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's second access key was created or last updated. If the user does not have a second active access key, the value in this field is `N/A` (not applicable). Applies to both account root user and IAM users.

**access\$1key\$12\$1last\$1used\$1date**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's second access key was most recently used to sign an AWS API request. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users.  
The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have a second access key.
+ The user's second access key has never been used.
+ The user's second access key was last used before IAM started tracking this information on April 22, 2015.

**access\$1key\$12\$1last\$1used\$1region**  
The [AWS Region](https://docs.aws.amazon.com/general/latest/gr/rande.html) in which the user's second access key was most recently used. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users. The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have a second access key.
+ The user's second access key has never been used.
+ The user's second access key was last used before IAM started tracking this information on April 22, 2015.
+ The last used service is not Region-specific, such as Amazon S3.

**access\$1key\$12\$1last\$1used\$1service**  
The AWS service that was most recently accessed with the user's second access key. The value in this field uses the service's namespace—for example, `s3` for Amazon S3 and `ec2` for Amazon EC2. When an access key is used more than once in a 15-minute span, only the first use is recorded in this field. Applies to both account root user and IAM users. The value in this field is `N/A` (not applicable) in these cases:  
+ The user does not have a second access key.
+ The user's second access key has never been used.
+ The user's second access key was last used before IAM started tracking this information on April 22, 2015.

**cert\$11\$1active**  
When the user has an X.509 signing certificate and that certificate's status is `Active`, this value is `TRUE`. Otherwise it is `FALSE`.

**cert\$11\$1last\$1rotated**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's signing certificate was created or last changed. If the user does not have an active signing certificate, the value in this field is `N/A` (not applicable).

**cert\$12\$1active**  
When the user has a second X.509 signing certificate and that certificate's status is `Active`, this value is `TRUE`. Otherwise it is `FALSE`.  
Users can have up to two X.509 signing certificates, to make certificate rotation easier.

**cert\$12\$1last\$1rotated**  
The date and time, in [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601), when the user's second signing certificate was created or last changed. If the user does not have a second active signing certificate, the value in this field is `N/A` (not applicable).

**additional\$1credentials\$1info**  
When the user has more than two access keys or certificates, this value is the number of additional access keys or certificates and the actions you can use to list the access keys or certificates associated with the user.

## Getting credential reports (console)


You can use the AWS Management Console to download a credential report as a comma-separated values (CSV) file.

**To download a credential report (console)**

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, choose **Credential report**.

1. Choose **Download Report**.

## Getting credential reports (AWS CLI)


**To download a credentials report (AWS CLI)**

1. Generate a credentials report. AWS stores a single report. If a report exists, generating a credentials report overwrites the previous report. [https://docs.aws.amazon.com/cli/latest/reference/iam/generate-credential-report.html](https://docs.aws.amazon.com/cli/latest/reference/iam/generate-credential-report.html)

1. View the last report that was generated: [https://docs.aws.amazon.com/cli/latest/reference/iam/get-credential-report.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-credential-report.html)

## Getting credential reports (AWS API)


**To download a credentials report (AWS API)**

1. Generate a credentials report. AWS stores a single report. If a report exists, generating a credentials report overwrites the previous report. [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateCredentialReport.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateCredentialReport.html)

1. View the last report that was generated: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetCredentialReport.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetCredentialReport.html)

# IAM credentials for CodeCommit: Git credentials, SSH keys, and AWS access keys
IAM credentials for CodeCommit

CodeCommit is a managed version control service that hosts private Git repositories in the AWS cloud. To use CodeCommit, you configure your Git client to communicate with CodeCommit repositories. As part of this configuration, you provide IAM credentials that CodeCommit can use to authenticate you. IAM supports CodeCommit with three types of credentials:
+ Git credentials, an IAM-generated user name and password pair you can use to communicate with CodeCommit repositories over HTTPS.
+ SSH keys, a locally generated public-private key pair that you can associate with your IAM user to communicate with CodeCommit repositories over SSH.
+  [AWS access keys](id_credentials_access-keys.md), which you can use with the credential helper included with the AWS CLI to communicate with CodeCommit repositories over HTTPS.

**Note**  
You cannot use SSH keys or Git credentials to access repositories in another AWS account. To learn how to configure access to CodeCommit repositories for IAM users and groups in another AWS account, see [Configure cross-account access to an AWS CodeCommit repository using roles](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html) in the *AWS CodeCommit User Guide*.

See the following sections for more information about each option. 

## Use Git credentials and HTTPS with CodeCommit (recommended)


With Git credentials, you generate a static user name and password pair for your IAM user, and then use those credentials for HTTPS connections. You can also use these credentials with any third-party tool or integrated development environment (IDE) that supports static Git credentials.

Because these credentials are universal for all supported operating systems and compatible with most credential management systems, development environments, and other software development tools, this is the recommended method. You can reset the password for Git credentials at any time. You can also make the credentials inactive or delete them if you no longer need them.

**Note**  
You cannot choose your own user name or password for Git credentials. IAM generates these credentials for you to help ensure they meet the security standards for AWS and secure repositories in CodeCommit. You can download the credentials only once, at the time they are generated. Make sure that you save the credentials in a secure location. If necessary, you can reset the password at any time, but doing so invalidates any connections configured with the old password. You must reconfigure connections to use the new password before you can connect.

See the following topics for more information: 
+ To create an IAM user, see [Create an IAM user in your AWS account](id_users_create.md). 
+ To generate and use Git credentials with CodeCommit, see [For HTTPS Users Using Git Credentials](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html) in the *AWS CodeCommit User Guide*. 

**Note**  
Changing the name of an IAM user after generating Git credentials does not change the user name of the Git credentials. The user name and password remain the same and are still valid. 

**To update service specific credentials**

1. Create a second service-specific credential set in addition to the set currently in use.

1. Update all of your applications to use the new set of credentials and validate that the applications are working.

1. Change the state of the original credentials to "Inactive".

1. Ensure that all of your applications are still working.

1. Delete the inactive service-specific credentials.

## Use SSH keys and SSH with CodeCommit


With SSH connections, you create public and private key files on your local machine that Git and CodeCommit use for SSH authentication. You associate the public key with your IAM user and store the private key on your local machine. See the following topics for more information: 
+ To create an IAM user, see [Create an IAM user in your AWS account](id_users_create.md). 
+ To create an SSH public key and associate it with an IAM user, see [For SSH Connections on Linux, macOS, or Unix](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-unixes.html) or see [For SSH Connections on Windows](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-windows.html) in the *AWS CodeCommit User Guide*. 

**Note**  
The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length of the public key is 2048 bits, and the maximum length is 16384 bits. This is separate from the size of the file you upload. For example, you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes long. If you provide your public key in another format or size, you will see an error message stating that the key format is not valid.

## Use HTTPS with the AWS CLI credential helper and CodeCommit


As an alternative to HTTPS connections with Git credentials, you can allow Git to use a cryptographically signed version of your IAM user credentials or Amazon EC2 instance role whenever Git needs to authenticate with AWS to interact with CodeCommit repositories. This is the only connection method for CodeCommit repositories that does not require an IAM user. This is also the only method that works with federated access and temporary credentials. See the following topics for more information:
+ To learn more about federated access, see [Identity providers and federation into AWS](id_roles_providers.md) and [Access to externally authenticated users (identity federation)](id_roles_common-scenarios_federated-users.md). 
+ To learn more about temporary credentials, see [Temporary security credentials in IAM](id_credentials_temp.md) and [Temporary Access to CodeCommit Repositories](https://docs.aws.amazon.com/codecommit/latest/userguide/temporary-access.html). 

The AWS CLI credential helper is not compatible with other credential helper systems, such as Keychain Access or Windows Credential Management. There are additional configuration considerations when you configure HTTPS connections with the credential helper. For more information, see [For HTTPS Connections on Linux, macOS, or Unix with the AWS CLI Credential Helper](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-https-unixes.html) or [HTTPS Connections on Windows with the AWS CLI Credential Helper](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-https-windows.html) in the *AWS CodeCommit User Guide*.

# Manage server certificates in IAM
Manage server certificates

To enable HTTPS connections to your website or application in AWS, you need an SSL/TLS *server certificate*. For certificates in a Region supported by AWS Certificate Manager (ACM), we recommend that you use ACM to provision, manage, and deploy your server certificates. In unsupported Regions, you must use IAM as a certificate manager. To learn which Regions ACM supports, see [AWS Certificate Manager endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/acm.html) in the *AWS General Reference*.

**Important**  
ACM is the preferred tool to provision, manage, and deploy your server certificates. With ACM you can request a certificate or deploy an existing ACM or external certificate to AWS resources. Certificates provided by ACM are free and automatically renew. In a [supported Region](https://docs.aws.amazon.com/general/latest/gr/acm.html), you can use ACM to manage server certificates from the console or programmatically. For more information about using ACM, see the [https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html). For more information about requesting an ACM certificate, see [Request a Public Certificate](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html) or [Request a Private Certificate](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-private.html) in the *AWS Certificate Manager User Guide*. For more information about importing third-party certificates into ACM, see [Importing Certificates](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) in the *AWS Certificate Manager User Guide*.

Use IAM as a certificate manager only when you must support HTTPS connections in a Region that is not [supported by ACM](https://docs.aws.amazon.com/general/latest/gr/acm.html). IAM securely encrypts your private keys and stores the encrypted version in IAM SSL certificate storage. IAM supports deploying server certificates in all Regions, but you must obtain your certificate from an external provider for use with AWS. You cannot upload an ACM certificate to IAM. Additionally, you cannot manage your certificates from the IAM Console.

For more information about uploading third-party certificates to IAM, see the following topics.

**Topics**
+ [

## Upload a server certificate (AWS API)
](#upload-server-certificate)
+ [

## AWS API operations for server certificates
](#id_credentials_server-certs-api)
+ [

## Troubleshoot server certificates
](#server-certificate-troubleshooting)

## Upload a server certificate (AWS API)


To upload a server certificate to IAM, you must provide the certificate and its matching private key. When the certificate is not self-signed, you must also provide a certificate chain. (You don't need a certificate chain when uploading a self-signed certificate.) Before you upload a certificate, ensure that you have all these items and that they meet the following criteria:
+ The certificate must be valid at the time of upload. You cannot upload a certificate before its validity period begins (the certificate's `NotBefore` date) or after it expires (the certificate's `NotAfter` date).
+ The private key must be unencrypted. You cannot upload a private key that is protected by a password or passphrase. For help decrypting an encrypted private key, see [Troubleshoot server certificates](#server-certificate-troubleshooting).
+ The certificate, private key, and certificate chain must all be PEM-encoded. For help converting these items to PEM format, see [Troubleshoot server certificates](#server-certificate-troubleshooting).

To use the [IAM API](https://docs.aws.amazon.com/IAM/latest/APIReference/) to upload a certificate, send an [UploadServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UploadServerCertificate.html) request. The following example shows how to do this with the [AWS Command Line Interface (AWS CLI)](https://aws.amazon.com/cli/). The example assumes the following:
+ The PEM-encoded certificate is stored in a file named `Certificate.pem`.
+ The PEM-encoded certificate chain is stored in a file named `CertificateChain.pem`.
+ The PEM-encoded, unencrypted private key is stored in a file named `PrivateKey.pem`.
+ (Optional) You want to tag the server certificate with a key–value pair. For example, you might add the tag key `Department` and the tag value `Engineering` to help you identify and organize your certificates.

To use the following example command, replace these file names with your own. Replace *ExampleCertificate* with a name for your uploaded certificate. If you want to tag the certificate, replace the *ExampleKey* and *ExampleValue* tag key-value pair with your own values. Type the command on one continuous line. The following example includes line breaks and extra spaces to make it easier to read.

```
aws iam upload-server-certificate --server-certificate-name ExampleCertificate
                                    --certificate-body file://Certificate.pem
                                    --certificate-chain file://CertificateChain.pem
                                    --private-key file://PrivateKey.pem
                                    --tags '{"Key": "ExampleKey", "Value": "ExampleValue"}'
```

When the preceding command is successful, it returns metadata about the uploaded certificate, including its [Amazon Resource Name (ARN)](reference_identifiers.md#identifiers-arns), its friendly name, its identifier (ID), its expiration date, tags, and more.

**Note**  
If you are uploading a server certificate to use with Amazon CloudFront, you must specify a path using the `--path` option. The path must begin with `/cloudfront` and must include a trailing slash (for example, `/cloudfront/test/`).

To use the AWS Tools for Windows PowerShell to upload a certificate, use [Publish-IAMServerCertificate](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Publish-IAMServerCertificate.html&tocid=Publish-IAMServerCertificate).

## AWS API operations for server certificates
AWS API operations

Use the following commands to view, tag, rename, and delete server certificates.
+ Use [GetServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetServerCertificate.html) to retrieve a certificate. This request returns the certificate, the certificate chain (if one was uploaded), and metadata about the certificate.
**Note**  
You cannot download or retrieve a private key from IAM after you upload it.
+ Use [Get-IAMServerCertificate](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Get-IAMServerCertificate.html&tocid=Get-IAMServerCertificate) to retrieve a certificate.
+ Use [ListServerCertificates](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServerCertificates.html) to list your uploaded server certificates. The request returns a list that contains metadata about each certificate.
+ Use [Get-IAMServerCertificates](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Get-IAMServerCertificates.html&tocid=Get-IAMServerCertificates) to list your uploaded server certificates.
+ Use [TagServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagServerCertificate.html) to tag an existing server certificate. 
+ Use [UntagServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagServerCertificate.html) to untag a server certificate.
+ Use [UpdateServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServerCertificate.html) to rename a server certificate or update its path.

   The following example shows how to do this with the AWS CLI.

  To use the following example command, replace the old and new certificate names and the certificate path, and type the command on one continuous line. The following example includes line breaks and extra spaces to make it easier to read.

  ```
  aws iam update-server-certificate --server-certificate-name ExampleCertificate
                                      --new-server-certificate-name CloudFrontCertificate
                                      --new-path /cloudfront/
  ```

  To use the AWS Tools for Windows PowerShell to rename a server certificate or update its path, use [Update-IAMServerCertificate](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Update-IAMServerCertificate.html&tocid=Update-IAMServerCertificate).
+ Use [DeleteServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServerCertificate.html) to delete a server certificate. 

  To use the AWS Tools for Windows PowerShell to delete a server certificate, use [Remove-IAMServerCertificate](https://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Remove-IAMServerCertificate.html&tocid=Remove-IAMServerCertificate).

## Troubleshoot server certificates


Before you can upload a certificate to IAM, you must make sure that the certificate, private key, and certificate chain are all PEM-encoded. You must also ensure that the private key is unencrypted. See the following examples.

**Example PEM-encoded certificate**  

```
-----BEGIN CERTIFICATE-----
Base64-encoded certificate
-----END CERTIFICATE-----
```

**Example PEM-encoded, unencrypted private key**  

```
-----BEGIN RSA PRIVATE KEY-----
Base64-encoded private key
-----END RSA PRIVATE KEY-----
```

**Example PEM-encoded certificate chain**  
A certificate chain contains one or more certificates. You can use a text editor, the copy command in Windows, or the Linux cat command to concatenate your certificate files into a chain. When you include multiple certificates, each certificate must certify the preceding certificate. You accomplish this by concatenating the certificates, including the root CA certificate last.  
The following example contains three certificates, but your certificate chain might contain more or fewer certificates.  

```
-----BEGIN CERTIFICATE-----
Base64-encoded certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Base64-encoded certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Base64-encoded certificate
-----END CERTIFICATE-----
```

If these items are not in the right format for uploading to IAM, you can use [OpenSSL](https://openssl.org/) to convert them to the right format.

**To convert a certificate or certificate chain from DER to PEM**  
Use the [OpenSSL **x509** command](https://openssl.org/docs/manmaster/man1/x509.html), as in the following example. In the following example command, replace `Certificate.der` with the name of the file that contains your DER-encoded certificate. Replace `Certificate.pem` with the preferred name of the output file to contain the PEM-encoded certificate.  

```
openssl x509 -inform DER -in Certificate.der -outform PEM -out Certificate.pem
```
 

**To convert a private key from DER to PEM**  
Use the [OpenSSL **rsa** command](https://openssl.org/docs/manmaster/man1/rsa.html), as in the following example. In the following example command, replace `PrivateKey.der` with the name of the file that contains your DER-encoded private key. Replace `PrivateKey.pem` with the preferred name of the output file to contain the PEM-encoded private key.  

```
openssl rsa -inform DER -in PrivateKey.der -outform PEM -out PrivateKey.pem
```
 

**To decrypt an encrypted private key (remove the password or passphrase)**  
Use the [OpenSSL **rsa** command](https://openssl.org/docs/manmaster/man1/rsa.html), as in the following example. To use the following example command, replace `EncryptedPrivateKey.pem` with the name of the file that contains your encrypted private key. Replace `PrivateKey.pem` with the preferred name of the output file to contain the PEM-encoded unencrypted private key.  

```
openssl rsa -in EncryptedPrivateKey.pem -out PrivateKey.pem
```
 

**To convert a certificate bundle from PKCS\$112 (PFX) to PEM**  
Use the [OpenSSL **pkcs12** command](https://openssl.org/docs/manmaster/man1/pkcs12.html), as in the following example. In the following example command, replace `CertificateBundle.p12` with the name of the file that contains your PKCS\$112-encoded certificate bundle. Replace `CertificateBundle.pem` with the preferred name of the output file to contain the PEM-encoded certificate bundle.  

```
openssl pkcs12 -in CertificateBundle.p12 -out CertificateBundle.pem -nodes
```
 

**To convert a certificate bundle from PKCS\$17 to PEM**  
Use the [OpenSSL **pkcs7** command](https://openssl.org/docs/manmaster/man1/pkcs7.html), as in the following example. In the following example command, replace `CertificateBundle.p7b` with the name of the file that contains your PKCS\$17-encoded certificate bundle. Replace `CertificateBundle.pem` with the preferred name of the output file to contain the PEM-encoded certificate bundle.  

```
openssl pkcs7 -in CertificateBundle.p7b -print_certs -out CertificateBundle.pem
```

# IAM user groups
User groups

An IAM [*user group*](#id_groups) is a collection of IAM users. User groups let you specify permissions for multiple users, which can make it easier to manage the permissions for those users. For example, you could have a user group called *Admins* and give that user group typical administrator permissions. Any user in that user group automatically has *Admins* group permissions. If a new user joins your organization and needs administrator privileges you can assign the appropriate permissions by adding the user to the *Admins* user group. If a person changes jobs in your organization, instead of editing that user's permissions you can remove them from the old IAM groups and add them to the appropriate new IAM groups. 

You can attach an identity-based policy to a user group so that all of the users in the user group receive the policy's permissions. You cannot identify a user group as a `Principal` in a policy (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities. For more information about policy types, see [Identity-based policies and resource-based policies](access_policies_identity-vs-resource.md).

Here are some important characteristics of IAM groups:
+ A user group can contain many users, and a user can belong to multiple user groups.
+ User groups can't be nested; they can contain only users, not other IAM groups.
+ There is no default user group that automatically includes all users in the AWS account. If you want to have a user group like that, you must create it and assign each new user to it.
+ The number and size of IAM resources in an AWS account, such as the number of groups, and the number of groups that a user can be a member of, are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md).

The following diagram shows a simple example of a small company. The company owner creates an `Admins` user group for users to create and manage other users as the company grows. The `Admins` user group creates a `Developers` user group and a `Test` user group. Each of these IAM groups consists of users (humans and applications) that interact with AWS (Jim, Brad, DevApp1, and so on). Each user has an individual set of security credentials. In this example, each user belongs to a single user group. However, users can belong to multiple IAM groups.

![\[Example of relationship between AWS accounts, users, and IAM groups\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/Relationship_Between_Entities_Example.diagram.png)


# Create IAM groups
Create IAM groups

**Note**  
As a [best practice](best-practices.md), we recommend that you require human users to use federation with an identity provider to access AWS using temporary credentials. If you follow the best practices, you are not managing IAM users and groups. Instead, your users and groups are managed outside of AWS and are able to access AWS resources as a *federated identity*. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. Federated identities use the groups defined by their identity provider. If you are using AWS IAM Identity Center, see [Manage identities in IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/manage-your-identity-source-sso.html) in the *AWS IAM Identity Center User Guide* for information about creating users and groups in IAM Identity Center.

You create IAM groups to manage access permissions for multiple users with similar roles or responsibilities. By attaching policies to these groups, you can grant or revoke permissions for entire sets of users. This simplifies your maintenance of security policies, as changes you make to a group's permissions are automatically applied to all members of that group, ensuring consistent access control. After you create the group, give the group permissions based on the type of work that you expect the IAM users in the group to do, then add the IAM users to the group.

For information about the permissions required to create an IAM group, see [Permissions required to access IAM resources](access_permissions-required.md). 

## To create an IAM group and attach policies


------
#### [ Console ]

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, choose **User groups** and then choose **Create group**.

1. For **User group name**, type the name of the group.
**Note**  
The number and size of IAM resources in an AWS account are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md). Group names can be a combination of up to 128 letters, digits, and these characters: plus (\$1), equal (=), comma (,), period (.), at sign (@), underscore (\$1), and hyphen (-). Names must be unique within an account. They aren't distinguished by case. For example, you cannot create groups named both **ADMINS** and **admins**.

1. In the list of users, select the check box for each user that you want to add to the group.

1. In the list of policies, select the check box for each policy that you want to apply to all members of the group.

1. Choose **Create group**.

------
#### [ AWS CLI ]

Run the following command:
+ [aws iam create-group](https://docs.aws.amazon.com/cli/latest/reference/iam/create-group.html)

------
#### [ API ]

Call the following operation:
+ [CreateGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html)

------

# View IAM groups


You can list all the IAM groups in your account, list the users in a user group, and list the IAM groups a user belongs to. If you use the CLI or API, you can list all the IAM groups with a particular path prefix.

------
#### [ Console ]

To list all IAM groups in your account:
+ In the navigation pane , choose **User groups**.

To list the IAM users in a specific IAM group:
+ In the navigation pane, choose **User groups**. Then choose the name of the group to open the group details page. Review the **Users** tab to see the group membership.

To list all the IAM groups that a user is in:
+ In the navigation pane, choose **Users**. Then choose the user name to open the user details page. Choose the **Groups** tab to see a list of the groups to which the user belongs.

------
#### [ AWS CLI ]

To list all IAM groups in your account:
+ [aws iam list-groups](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups.html)

To list the users in a specific IAM group:
+ [aws iam get-group](https://docs.aws.amazon.com/cli/latest/reference/iam/get-group.html)

To list all the IAM groups that a user is in:
+ [aws iam list-groups-for-user](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups-for-user.html)

------
#### [ API ]

To list all IAM groups in your account:
+ [ListGroups](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html)

To list the users in a specific IAM group:
+ [GetGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetGroup.html)

To list all the IAM groups that a user is in:
+ [ListGroupsForUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html)

------

# Edit users in IAM groups
Edit users in IAM groups

Use IAM groups to apply the same permissions policies across multiple users at once. You can then add users to or remove users from an IAM group. This is useful as people enter and leave your organization.

## Review policy access


Before you remove a group, use the group details page to review the members (IAM users) of the group, the policies attached to the group on the **Permissions** tab and review recent service-level activity using the **Last Accessed** tab. This helps prevent unintentionally removing access from a principal (person or application) who is using it. For more information about viewing last accessed information, see [Refine permissions in AWS using last accessed information](access_policies_last-accessed.md).

## Add an IAM user to an IAM group


------
#### [ Console ]

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, choose **User groups** and then choose the name of the group.

1. Choose the **Users** tab and then choose **Add users**. Select the check box next to the users you want to add.

1. Choose **Add users**.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam add-user-to-group](https://docs.aws.amazon.com/cli/latest/reference/iam/add-user-to-group.html)`

------
#### [ API ]

Call the following operation:
+ `[AddUserToGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html)`

------

## Remove an IAM user from an IAM group


------
#### [ Console ]

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, choose **User groups** and then choose the name of the group.

1. Choose the **Users** tab. Select the check box next to the users you want to remove and then choose **Remove users**.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam remove-user-from-group](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-user-from-group.html)`

------
#### [ API ]

Call the following operation:
+ `[RemoveUserFromGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html)`

------

# Attach a policy to an IAM user group
Attach a policy to a user group

You can attach an [AWS managed policy](access_policies_managed-vs-inline.md#aws-managed-policies)—that is, a prewritten policy provided by AWS—to a user group, as explained in the following steps. To attach a customer managed policy—that is, a policy with custom permissions that you create—you must first create the policy. For information about creating customer managed policies, see [Define custom IAM permissions with customer managed policies](access_policies_create.md). 

For more information about permissions and policies, see [Access management for AWS resources](access.md). 

## To attach a policy to an IAM group


------
#### [ Console ]

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, choose **User groups** and then choose the name of the group.

1. Choose the **Permissions** tab.

1. Choose **Add permissions** and then choose **Attach policies**.

1. The current policies attached to the user group are displayed in the **Current permissions policies** list. In the list of **Other permissions policies**, select the check box next to the names of the policies to attach. You can use the search box to filter the list of policies by type and policy name.

1. Select the policy you want to attach to your IAM group and choose **Attach policies**.

------
#### [ AWS CLI ]

Run the following command:
+ `[aws iam attach-group-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-group-policy.html)`

------
#### [ API ]

Call the following operation:
+ `[AttachGroupPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachGroupPolicy.html)`

------

# Rename an IAM user group
Rename a user group

When you change a user group's name or path, the following happens: 
+ Any policies attached to the user group stay with the group under the new name.
+ The user group retains all its users under the new name.
+ The unique ID for the user group remains the same. For more information about unique IDs, see [Unique identifiers](reference_identifiers.md#identifiers-unique-ids). 

IAM does not automatically update policies that refer to the user group as a resource to use the new name. Therefore, you must be careful when you rename a user group. Before you rename your user group, you must manually check all of your policies to find any policies where that user group is mentioned by name. For example, let's say Bob is the manager of the testing part of the organization. Bob has a policy attached to his IAM user entity that lets him add and remove users from the Test user group. If an administrator changes the name of the user group (or changes the group path), the administrator must also update the policy attached to Bob to use the new name or path. Otherwise Bob won't be able to add and remove users from the user group. 

**To find policies that refer to an IAM group as a resource:**

1. From the navigation pane of the IAM console, choose **Policies**.

1. Sort by the **Type** column to find your **Customer managed** custom policies.

1. Choose the policy name of the policy to edit.

1. Choose the **Permissions** tab, and then choose **Summary**.

1. Choose **IAM** from the list of services, if it exists.

1. Look for the name of your user group in the **Resource** column.

1. Choose **Edit** to change the name of your user group in the policy.

## To change the name of an IAM user group


------
#### [ Console ]

1. In the navigation pane, select **User groups** and then select the group name.

1. Choose **Edit**. Type the new user group name and then choose **Save changes**.

------
#### [ AWS CLI ]

Run the following command:
+ [aws iam update-group](https://docs.aws.amazon.com/cli/latest/reference/iam/update-group.html)

------
#### [ API ]

Call the following operation:
+ [UpdateGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateGroup.html)

------

# Delete an IAM group
Delete an IAM group

When you delete an IAM group in the console, the console automatically removes all group members, detaches all attached managed policies, and deletes all inline policies. However, because IAM doesn't automatically delete policies that refer to the IAM group as a resource, you must be careful when you delete an IAM group. Before you delete your IAM group, manually review your policies to find any policies that mention the group by name. For example, John, the Test Team manager, has a policy attached to his IAM user entity that lets him add and remove users from the Test user group. If an administrator deletes the group, the administrator must also delete the policy attached to John. Otherwise, if the administrator recreates the deleted group and give it the same name, John's permissions remain in place, even if he left the Test Team.

In contrast, when you use the CLI, SDK, or API to delete a user group, you remove the users in the group first. Then you delete any inline policies embedded in the IAM group. Next, you detach any managed policies that are attached to the group. Then you delete the IAM group itself.

------
#### [ Console ]

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, choose **User groups**.

1. In the list of IAM groups, select the check box next to the names of the IAM groups to delete. You can use the search box to filter the list of IAM groups by type, permissions, and group name.

1. Choose **Delete**.

1. In the confirmation box, if you want to delete a single group, type the group name and choose **Delete**. If you want to delete multiple groups, type the number of IAM group to delete followed by **user groups** and choose **Delete**. For example, if you want to delete three groups, type **3 **user groups****.

------
#### [ AWS CLI ]

1. Remove all users from the IAM group.
   + [aws iam get-group](https://docs.aws.amazon.com/cli/latest/reference/iam/get-group.html) (to get the list of users in the IAM group), and [aws iam remove-user-from-group](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-user-from-group.html) (to remove a user from the IAM group)

1. Delete all inline policies embedded in the IAM group.
   + [aws iam list-group-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-group-policies.html) (to get a list of the IAM group's inline policies), and [aws iam delete-group-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-group-policy.html) (to delete the IAM group's inline policies)

1. Detach all managed policies attached to the IAM group.
   + [aws iam list-attached-group-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-group-policies.html) (to get a list of the managed policies attached to the IAM group), and [aws iam detach-group-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/detach-group-policy.html) (to detach a managed policy from the IAM group)

1. Delete the IAM group.
   + [aws iam delete-group](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-group.html)

------
#### [ API ]

1. Remove all users from the IAM group.
   + [GetGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetGroup.html) (to get the list of users in the IAM group) and [RemoveUserFromGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html) (to remove a user from the IAM group)

1. Delete all inline policies embedded in the IAM group.
   + [ListGroupPolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupPolicies.html) (to get a list of the IAM group's inline policies) and [DeleteGroupPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroupPolicy.html) (to delete the IAM group's inline policies)

1. Detach all managed policies attached to the IAM group.
   + [ListAttachedGroupPolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedGroupPolicies.html) (to get a list of the managed policies attached to the IAM group) and [DetachGroupPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachGroupPolicy.html) (to detach a managed policy from the IAM group)

1. Delete the IAM group.
   + [DeleteGroup](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroup.html)

------

# IAM roles
Roles

An IAM *role* is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS. However, instead of being uniquely associated with one person, a role is intended to be assumable by anyone who needs it. Also, a role does not have standard long-term credentials such as a password or access keys associated with it. Instead, when you assume a role, it provides you with temporary security credentials for your role session.

You can use roles to delegate access to users, applications, or services that don't normally have access to your AWS resources. For example, you might want to grant users in your AWS account access to resources they don't usually have, or grant users in one AWS account access to resources in another account. Or you might want to allow a mobile app to use AWS resources, but not want to embed AWS keys within the app (where they can be difficult to update and where users can potentially extract them). Sometimes you want to give AWS access to users who already have identities defined outside of AWS, such as in your corporate directory. Or, you might want to grant access to your account to third parties so that they can perform an audit on your resources.

For these scenarios, you can delegate access to AWS resources using an *IAM role*. This section introduces roles and the different ways you can use them, when and how to choose among approaches, and how to create, manage, switch to (or assume), and delete roles.

**Note**  
When you first create your AWS account, no roles are created by default. As you add services to your account, they may add service-linked roles to support their use cases.  
 A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles.   
Before you can delete service-linked roles you must first delete their related resources. This protects your resources because you can't inadvertently remove permission to access the resources.  
For information about which services support using service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-Linked Role** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

**Topics**
+ [

## When to create an IAM user (instead of a role)
](#id_which-to-choose)
+ [

## Roles terms and concepts
](#id_roles_terms-and-concepts)
+ [

## Additional resources
](#id_roles_additional-resources)
+ [

# The confused deputy problem
](confused-deputy.md)
+ [

# Common scenarios for IAM roles
](id_roles_common-scenarios.md)
+ [

# IAM role creation
](id_roles_create.md)
+ [

# IAM role management
](id_roles_manage.md)
+ [

# Methods to assume a role
](id_roles_manage-assume.md)

## When to create an IAM user (instead of a role)


We recommend you only use IAM users for use cases not supported by identity federation. Some of the use cases include the following:
+ **Workloads that cannot use IAM roles** – You might run a workload from a location that needs to access AWS. In some situations, you can't use IAM roles to provide temporary credentials, such as for WordPress plugins. In these situations, use IAM user long-term access keys for that workload to authenticate to AWS.
+ **Third-party AWS clients** – If you are using tools that don’t support access with IAM Identity Center, such as third-party AWS clients or vendors that aren't hosted on AWS, use IAM user long-term access keys.
+ **AWS CodeCommit access** – If you are using CodeCommit to store your code, you can use an IAM user with either SSH keys or service-specific credentials for CodeCommit to authenticate to your repositories. We recommend that you do this in addition to using a user in IAM Identity Center for normal authentication. Users in IAM Identity Center are the people in your workforce who need access to your AWS accounts or to your cloud applications. To give users access to your CodeCommit repositories without configuring IAM users, you can configure the **git-remote-codecommit** utility. For more information about IAM and CodeCommit, see [IAM credentials for CodeCommit: Git credentials, SSH keys, and AWS access keys](id_credentials_ssh-keys.md). For more information about configuring the **git-remote-codecommit** utility, see [Connecting to AWS CodeCommit repositories with rotating credentials](https://docs.aws.amazon.com/codecommit/latest/userguide/temporary-access.html#temporary-access-configure-credentials) in the *AWS CodeCommit User Guide*.
+ **Amazon Keyspaces (for Apache Cassandra) access** – In a situation where you are unable to use users in IAM Identity Center, such as for testing purposes for Cassandra compatibility, you can use an IAM user with service-specific credentials to authenticate with Amazon Keyspaces. Users in IAM Identity Center are the people in your workforce who need access to your AWS accounts or to your cloud applications. You can also connect to Amazon Keyspaces using temporary credentials. For more information, see [Using temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin](https://docs.aws.amazon.com/keyspaces/latest/devguide/access.credentials.html#temporary.credentials.IAM) in the *Amazon Keyspaces (for Apache Cassandra) Developer Guide*.
+ **Emergency access** – In a situation where you can't access your identity provider and you must take action in your AWS account. Establishing emergency access IAM users can be part of your resiliency plan. We recommend that the emergency user credentials be tightly controlled and secured using multi-factor authentication (MFA).

## Roles terms and concepts


Here are some basic terms to help you get started with roles.

****Role****  
An IAM identity that you can create in your account that has specific permissions. An IAM role has some similarities to an IAM user. Roles and users are both AWS identities with permissions policies that determine what the identity can and cannot do in AWS. However, instead of being uniquely associated with one person, a role is intended to be assumable by anyone who needs it. Also, a role does not have standard long-term credentials such as a password or access keys associated with it. Instead, when you assume a role, it provides you with temporary security credentials for your role session.  
Roles can be assumed by the following:  
+ An IAM user in the same AWS account or another AWS account
+ IAM roles in the same account
+ Service principals, for use with AWS services and features like:
  + Services that allow you to run code on compute services, like Amazon EC2 or AWS Lambda
  + Features that perform actions to your resources on your behalf, like Amazon S3 object replication
  + Services that deliver temporary security credentials to your applications that run outside of AWS, such as IAM Roles Anywhere or Amazon ECS Anywhere
+ An external user authenticated by an external identity provider (IdP) service that is compatible with SAML 2.0 or OpenID Connect

****AWS service role****  
 A service role is an [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see [Create a role to delegate permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*. 

****AWS service-linked role****  
 A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles.   
If you are already using a service when it begins supporting service-linked roles, you might receive an email announcing a new role in your account. In this case, the service automatically created the service-linked role in your account. You don't need to take any action to support this role, and you should not manually delete it. For more information, see [A new role appeared in my AWS account](troubleshoot_roles.md#troubleshoot_roles_new-role-appeared).
For information about which services support using service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-Linked Role** column. Choose a **Yes** with a link to view the service-linked role documentation for that service. For more information, see [Create a service-linked role](id_roles_create-service-linked-role.md).

****Role chaining****  
Role chaining is when you use a role to assume a second role. You can perform role chaining through the AWS Management Console by switching roles, the AWS CLI, or API. For example, `RoleA` has permission to assume `RoleB`. You can enable User1 to assume `RoleA` by using their long-term user credentials in the AssumeRole API operation. This returns `RoleA` short-term credentials. With role chaining, you can use `RoleA`'s short-term credentials to enable User1 to assume `RoleB`.  
When you assume a role, you can pass a session tag and set the tag as transitive. Transitive session tags are passed to all subsequent sessions in a role chain. To learn more about session tags, see [Pass session tags in AWS STS](id_session-tags.md).  
Role chaining limits your AWS Management Console, AWS CLI or AWS API role session to a maximum of one hour. It applies regardless of the maximum session duration configured for individual roles. When you use the [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation to assume a role, you can specify the duration of your role session with the `DurationSeconds` parameter. You can specify a parameter value of up to 43200 seconds (12 hours), depending on the [maximum session duration setting](id_roles_update-role-settings.md#id_roles_update-session-duration) for your role. However, if you assume a role using role chaining and provide a `DurationSeconds` parameter value greater than one hour, the operation fails.  
For information about switching to a role in the AWS Management Console, see [Switch from a user to an IAM role (console)](id_roles_use_switch-role-console.md).

****Delegation****  
The granting of permissions to someone to allow access to resources that you control. Delegation involves setting up a trust between two accounts. The first is the account that owns the resource (the trusting account). The second is the account that contains the users that need to access the resource (the trusted account). The trusted and trusting accounts can be any of the following:  
+ The same account.
+ Separate accounts that are both under your organization's control.
+ Two accounts owned by different organizations.
To delegate permission to access a resource, you [create an IAM role](id_roles_create_for-user.md) in the trusting account that has two policies attached. The *permissions policy* grants the user of the role the needed permissions to carry out the intended tasks on the resource. The *trust policy* specifies which trusted account members are allowed to assume the role.  
When you create a trust policy, you cannot specify a wildcard (\$1) as part of and ARN in the principal element. The trust policy is attached to the role in the trusting account, and is one-half of the permissions. The other half is a permissions policy attached to the user in the trusted account that [allows that user to switch to, or assume the role](id_roles_use_permissions-to-switch.md). A user who assumes a role temporarily gives up his or her own permissions and instead takes on the permissions of the role. When the user exits, or stops using the role, the original user permissions are restored. An additional parameter called [external ID](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) helps ensure secure use of roles between accounts that are not controlled by the same organization.

****Trust policy****  
A [JSON policy document](reference_policies_grammar.md) in which you define the principals that you *trust* to assume the role. A role trust policy is a required [resource-based policy](access_policies.md#policies_resource-based) that is attached to a role in IAM. The [principals](reference_policies_elements_principal.md) that you can specify in the trust policy include users, roles, accounts, and services. For more information, see [How to use trust policies in IAM roles](https://aws.amazon.com/blogs//security/how-to-use-trust-policies-with-iam-roles/) in *AWS Security Blog*.

****Role for cross-account access****  
A role that grants access to resources in one account to a trusted principal in a different account. Roles are the primary way to grant cross-account access. However, some AWS services allow you to attach a policy directly to a resource (instead of using a role as a proxy). These are called resource-based policies, and you can use them to grant principals in another AWS account access to the resource. Some of these resources include Amazon Simple Storage Service (S3) buckets, Amazon Glacier vaults, Amazon Simple Notification Service (SNS) topics, and Amazon Simple Queue Service (SQS) queues. To learn which services support resource-based policies, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md). For more information about resource-based policies, see [Cross account resource access in IAM](access_policies-cross-account-resource-access.md).

## Additional resources


The following resources can help you learn more about IAM terminology related to IAM roles.
+ **Principals** are entities in AWS that can perform actions and access resources. A principal can be an AWS account root user, an IAM user, or a role. A principal that represents the identity of an AWS service is a [service principal](reference_policies_elements_principal.md#principal-services). Use the Principal element in role trust policies to define the principals that you trust to assume the role.

   For more information and examples of principals you can allow to assume a role, see [AWS JSON policy elements: Principal](reference_policies_elements_principal.md). 
+ **Identity federation** creates a trust relationship between an external identity provider and AWS. You can use your existing OpenID Connect (OIDC) or Security Assertion Markup Language (SAML) 2.0 provider to manage who can access AWS resources. When you use OIDC and SAML 2.0 to configure a trust relationship between these external identity providers and AWS , the user is assigned to an IAM role. The user also receives temporary credentials that allow the user to access your AWS resources.

  For more information about federated principals, see [Identity providers and federation into AWS](id_roles_providers.md).
+ **Federated principals** are existing identities from Directory Service, your enterprise user directory, or an OIDC provider. AWS assigns a role to a federated principal when access is requested through an [identity provider](id_roles_providers.md).

  For more information about SAML and OIDC federated principals, see [Federated user sessions and roles](introduction_access-management.md#intro-access-roles).
+ **Permissions policies** are identity-based policies that define what actions and resources the role can use. The document is written according to the rules of the IAM policy language. 

  For more information, see [IAM JSON policy reference](reference_policies.md).
+ **Permissions boundaries** are an advanced feature in which you use policies to limit the maximum permissions that an identity-based policy can grant to a role. You cannot apply a permissions boundary to a service-linked role.

  For more information, see [Permissions boundaries for IAM entities](access_policies_boundaries.md).

# The confused deputy problem


The confused deputy problem is a security issue where an entity that doesn't have permission to perform an action can coerce a more-privileged entity to perform the action. To prevent this, AWS provides tools that help you protect your account if you provide third parties (known as *cross-account*) or other AWS services (known as *cross-service*) access to resources in your account.

At times, you might need to give a third party access to your AWS resources (delegate access). For example, you decide to hire a third-party company called Example Corp to monitor your AWS account and help optimize costs. In order to track your daily spending, Example Corp needs to access your AWS resources. Example Corp also monitors many other AWS accounts for other customers. You can use an IAM role to establish a trusted relationship between your AWS account and the Example Corp account. One important aspect of this scenario is the *external ID*, an optional identifier that you can use in an IAM role trust policy to designate who can assume the role. The primary function of the external ID is to address and prevent the confused deputy problem.

Some AWS services (calling services) use their AWS service principal to access AWS resources from other AWS services (called services). In some of these service interactions you can configure calling services to communicate with the resources from a called service in a different AWS account. An example of this is configuring AWS CloudTrail to write to a central Amazon S3 bucket which is located in a different AWS account. The calling service, CloudTrail is granted access to your S3 bucket using the S3 bucket’s policy by adding an allow statement for `cloudtrail.amazonaws.com`.

When an AWS service principal from a calling service is accessing a resource from a called service, the resource policy from the called service is only authorizing the AWS service principal, and not the actor who configured the calling service. For example, an S3 bucket that trusts the CloudTrail service principal with no conditions could receive CloudTrail logs from the AWS accounts that a trusted admin configures, but also CloudTrail logs from an unauthorized actor in their AWS account, if they know the name of the S3 bucket.

The confused deputy problem arises when an actor uses the trust of an AWS service’s service principal to gain access to resources that they are not intended to have access to.

## Cross-account confused deputy prevention


The following diagram illustrates the cross-account confused deputy problem.

![\[The description of a confused deputy problem.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/confuseddeputyproblem2.png)


This scenario assumes the following:
+ **AWS1** is your AWS account.
+ **AWS1:ExampleRole** is a role in your account. This role's trust policy trusts Example Corp by specifying Example Corp's AWS account as the one that can assume the role.

Here's what happens:

1. When you start using Example Corp's service, you provide the ARN of **AWS1:ExampleRole** to Example Corp.

1. Example Corp uses that role ARN to obtain temporary security credentials to access resources in your AWS account. In this way, you are trusting Example Corp as a "deputy" that can act on your behalf.

1. Another AWS customer also starts using Example Corp's service, and this customer also provides the ARN of **AWS1:ExampleRole** for Example Corp to use. Presumably the other customer learned or guessed the **AWS1:ExampleRole**, which isn't a secret.

1. When the other customer asks Example Corp to access AWS resources in (what it claims to be) its account, Example Corp uses **AWS1:ExampleRole** to access resources in your account.

This is how the other customer could gain unauthorized access to your resources. Because this other customer was able to trick Example Corp into unwittingly acting on your resources, Example Corp is now a "confused deputy."

Example Corp can address the confused deputy problem by requiring that you include the `ExternalId` condition check in the role's trust policy. Example Corp generates a unique `ExternalId` value for each customer and uses that value in its request to assume the role. The `ExternalId` value must be unique among Example Corp's customers and controlled by Example Corp, not its customers. This is why you get it from Example Corp and you don't come up with it on your own. This prevents Example Corp from being a confused deputy and granting access to another account's AWS resources.

In our scenario, imagine Example Corp's unique identifier for you is 12345, and its identifier for the other customer is 67890. These identifiers are simplified for this scenario. Generally, these identifiers are GUIDs. Assuming that these identifiers are unique among Example Corp's customers, they are sensible values to use for the external ID. 

Example Corp gives the external ID value of 12345 to you. You must then add a `Condition` element to the role's trust policy that requires the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts) value to be 12345, like this:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {
      "AWS": "Example Corp's AWS Account ID"
    },
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": {
        "sts:ExternalId": "12345"
      }
    }
  }
}
```

------

The Condition element in this policy allows Example Corp to assume the role only when the AssumeRole API call includes the external ID value of 12345. Example Corp makes sure that whenever it assumes a role on behalf of a customer, it always includes that customer's external ID value in the AssumeRole call. Even if another customer supplies Example Corp with your ARN, it cannot control the external ID that Example Corp includes in its request to AWS. This helps prevent an unauthorized customer from gaining access to your resources.

The following diagram illustrates this.

![\[How to mitigate a confused deputy problem.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/confuseddeputymitigation2.png)


1. As before, when you start using Example Corp's service, you provide the ARN of **AWS1:ExampleRole** to Example Corp.

1.  When Example Corp uses that role ARN to assume the role **AWS1:ExampleRole**, Example Corp includes your external ID (12345) in the AssumeRole API call. The external ID matches the role's trust policy, so the AssumeRole API call succeeds and Example Corp obtains temporary security credentials to access resources in your AWS account.

1. Another AWS customer also starts using Example Corp's service, and as before, this customer also provides the ARN of **AWS1:ExampleRole** for Example Corp to use. 

1. But this time, when Example Corp attempts to assume the role **AWS1:ExampleRole**, it provides the external ID associated with the other customer (67890). The other customer has no way to change this. Example Corp does this because the request to use the role came from the other customer, so 67890 indicates the circumstance in which Example Corp is acting. Because you added a condition with your own external ID (12345) to the trust policy of **AWS1:ExampleRole**, the AssumeRole API call fails. The other customer is prevented from gaining unauthorized access to resources in your account (indicated by the red "X" in the diagram).

The external ID helps prevent any other customer from tricking Example Corp into unwittingly accessing your resources.

## Cross-service confused deputy prevention


The following diagram demonstrates the cross-service confused deputy problem using the CloudTrail and Amazon S3 interaction example, where an unauthorized actor writes CloudTrail logs to an Amazon S3 bucket they are not authorized to have access to.

![\[An unauthorized actor is granted access to an Amazon S3 bucket in another account using the CloudTrail service principal.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/cross-service-confused-deputy1.png)


To help protect against an unauthorized actor from using the trust of an AWS principal to gain access to your resources, AWS service principals include information about the AWS resource, AWS account, and AWS organization they’re acting on behalf of.

This information is available in global condition key values that can be used in a resource policy, or resource control policy for requests made by AWS service principals. We recommend using [aws:SourceArn](reference_policies_condition-keys.md#condition-keys-sourcearn), [aws:SourceAccount](reference_policies_condition-keys.md#condition-keys-sourceaccount), [aws:SourceOrgID](reference_policies_condition-keys.md#condition-keys-sourceorgid), or [aws:SourceOrgPaths](reference_policies_condition-keys.md#condition-keys-sourceorgpaths) in your resource policies wherever an AWS service principal is granted permission to access one of your resources. These condition keys allow you to test in your resource policies, or resource control policies that AWS service principals accessing your resources are doing so on behalf of AWS resources, AWS accounts, or AWS Organizations you expect.
+ Use `aws:SourceArn` to allow an AWS service principal to access your resources on behalf of a specific resource, such as a specific AWS CloudTrail trail or AppStream fleet.
+ Use `aws:SourceAccount` to allow an AWS service principal to access your resources on behalf of a specific AWS account.
+ Use `aws:SourceOrgID` to allow an AWS service principal to access your resources on behalf of specific AWS Organizations.
+ Use `aws:SourceOrgPaths` to allow AWS service principal to access your resources on behalf of a specific AWS Organizations path.

The following diagram demonstrates the cross-service confused deputy scenario when a resource is configured with the `aws:SourceAccount` global condition context key, and an unauthorized actor from another account tries to access AWS resources they are not intended to have access to.

![\[An unauthorized actor is denied access to an Amazon S3 bucket in another account using the CloudTrail service principal.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/cross-service-confused-deputy2.png)


Using `aws:SourceArn`, `aws:SourceAccount`, `aws:SourceOrgID`, and `aws:SourceOrgPaths` global condition keys in a policy help you ensure service principals are accessing your resources on your behalf. We recommend using these condition keys whenever access to one of your resources is granted to an AWS service principal. 

**Note**  
Some AWS service interactions have additional controls to help protect against cross-service confused deputy issues that test user access to a resource. For example, when a KMS key grant is issued to an AWS service, AWS KMS uses the encryption context associated with the resource, and the key grant to help protect against cross-service confused deputy issues.  
Please see the documentation of the services you use for more information about service-specific mechanisms that can help avoid cross-service confused deputy risks, and whether `aws:SourceArn`, `aws:SourceAccount`, `aws:SourceOrgID`, and `aws:SourceOrgPaths` are supported.

## Cross-service confused deputy protection with resource-based policies


The following example policy grants the service principal `cloudtrail.amazonaws.com` access to the Amazon S3 bucket, arn:aws:s3:::amzn-s3-demo-bucket1, only when the service principal is acting on behalf of AWS account 111122223333.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "CloudTrailAclCheck",
            "Effect": "Allow",
            "Principal": {"Service": "cloudtrail.amazonaws.com"},
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket1",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        },
        {
            "Sid": "AWSCloudTrailWrite",
            "Effect": "Allow",
            "Principal": {"Service": "cloudtrail.amazonaws.com"},
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket1/[optionalPrefix]/Logs/myAccountID/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        }
    ]
}
```

------

This example bucket policy grants the service principal `appstream.amazonaws.com` access to the powershell script examplefile.psh within the s3://amzn-s3-demo-bucket2 only when it is acting on behalf of the specified Amazon AppStream fleet, by specifying the fleet arn with `aws:SourceArn`.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "appstream.amazonaws.com"
                ]
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket2/examplefile.psh",
            "Condition": {
                "ArnEquals": {
                    "aws:SourceArn": "arn:aws:appstream:us-east-1:111122223333:fleet/ExampleFleetName"
                } 
            }
        }
    ]
}
```

------

## Cross-service confused deputy protection with resource control policies


You can use resource control policies (RCP) to apply cross-service confused deputy controls to resources of supported AWS services. RCPs allow you to centrally apply cross-service confused deputy controls on your resources. You can use condition keys like `aws:SourceOrgId` and `aws:SourceOrgPaths` with RCPs attached to your AWS Organizations, organization units (OU) or AWS accounts in your organization without adding statements to specific resource-based policies. For more information about RCPs and supported services, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the *AWS Organizations User Guide*.

The following example RCP denies AWS service principals access to Amazon S3 buckets in your member accounts when `aws:SourceOrgID` is not equal to o-ExampleOrg. A corresponding allow must be present in the resource-based policy of the S3 bucket to allow AWS service principals with a `SourceOrgID` equal to o-ExampleOrg.

This policy applies the control only on requests by service principals (`"Bool": {"aws:PrincipalIsAWSService": "true"}`) that have the `aws:SourceAccount` key present (`"Null": {"aws:SourceAccount": "false"}`), so that service integrations that don't require the use of the condition key and calls by your principals aren't impacted. If the `aws:SourceAccount` condition key is present in the request context, the Null condition will evaluate to true, causing `aws:SourceOrgID` to be enforced. We use `aws:SourceAccount` instead of `aws:SourceOrgID` in the Null condition operator so that the control still applies if the request originates from an account that doesn’t belong to an organization.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "RCPEnforceConfusedDeputyProtectionForS3",
      "Effect": "Deny",
      "Principal": "*",
      "Action": [
        "s3:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringNotEqualsIfExists": {
          "aws:SourceOrgID": "o-ExampleOrg"
        },
        "Null": {
          "aws:SourceAccount": "false"
        },
        "Bool": {
          "aws:PrincipalIsAWSService": "true"
        }
      }
    }
  ]
}
```

------

# Common scenarios for IAM roles
Common scenarios

As with most AWS features, you generally have two ways to use a role: interactively in the IAM console, or programmatically with the AWS CLI, Tools for Windows PowerShell, or API.
+ IAM users in your account using the IAM console can *switch to* a role to temporarily use the permissions of the role in the console. The users give up their original permissions and take on the permissions assigned to the role. When the users exit the role, their original permissions are restored.
+ An application or a service offered by AWS (like Amazon EC2) can *assume* a role by requesting temporary security credentials for a role with which to make programmatic requests to AWS. You use a role this way so that you don't have to share or maintain long-term security credentials (for example, by creating an IAM user) for each entity that requires access to a resource.

**Note**  
This guide uses the phrases *switch to a role* and *assume a role* interchangeably.

The simplest way to use roles is to grant your IAM users permissions to switch to roles that you create within your own or another AWS account. They can switch roles easily using the IAM console to use permissions that you don't ordinarily want them to have, and then exit the role to surrender those permissions. This can help prevent *accidental* access to or modification of sensitive resources.

For more complex uses of roles, such as granting access to applications and services, or federated external users, you can call the `AssumeRole` API. This API call returns a set of temporary credentials that the application can use in subsequent API calls. Actions attempted with the temporary credentials have only the permissions granted by the associated role. An application doesn't have to "exit" the role the way a user in the console does; rather the application simply stops using the temporary credentials and resumes making calls with the original credentials.

Federated users sign in by using credentials from an identity provider (IdP). AWS then provides temporary credentials to the trusted IdP to pass on to the user for including in subsequent AWS resource requests. Those credentials provide the permissions granted to the assigned role.

This section provides overviews of the following scenarios:
+ [Provide access for an IAM user in one AWS account that you own to access resources in another account that you own](id_roles_common-scenarios_aws-accounts.md)
+ [Provide access to non AWS workloads](id_roles_common-scenarios_non-aws.md)
+ [Provide access to IAM users in AWS accounts owned by third parties](id_roles_common-scenarios_third-party.md)
+ [Provide access for services offered by AWS to AWS resources](id_roles_common-scenarios_services.md)
+ [Provide access for externally authenticated users (identity federation)](id_roles_common-scenarios_federated-users.md)

# Access for an IAM user in another AWS account that you own
Access across AWS accounts

You can grant your IAM users permission to switch to roles within your AWS account or to roles defined in other AWS accounts that you own. 

**Note**  
If you want to grant access to an account that you do not own or control, see [Access to AWS accounts owned by third parties](id_roles_common-scenarios_third-party.md) later in this topic. 

Imagine that you have Amazon EC2 instances that are critical to your organization. Instead of directly granting your users permission to terminate the instances, you can create a role with those privileges. Then allow administrators to switch to the role when they need to terminate an instance. Doing this adds the following layers of protection to the instances:
+ You must explicitly grant your users permission to assume the role.
+ Your users must actively switch to the role using the AWS Management Console or assume the role using the AWS CLI or AWS API.
+ You can add multi-factor authentication (MFA) protection to the role so that only users who sign in with an MFA device can assume the role. To learn how to configure a role so that users who assume the role must first be authenticated using multi-factor authentication (MFA), see [Secure API access with MFA](id_credentials_mfa_configure-api-require.md).

We recommend using this approach to enforce the *principle of least privilege*. That means restricting the use of elevated permissions to only those times when they are needed for specific tasks. With roles you can help prevent accidental changes to sensitive environments, especially if you combine them with [auditing](cloudtrail-integration.md) to help ensure that roles are only used when needed.

When you create a role for this purpose, you specify the accounts by ID whose users need access in the `Principal` element of the role's trust policy. You can then grant specific users in those other accounts permissions to switch to the role. To learn whether principals in accounts outside of your zone of trust (trusted organization or account) have access to assume your roles, see [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html).

A user in one account can switch to a role in the same or a different account. While using the role, the user can perform only the actions and access only the resources permitted by the role; their original user permissions are suspended. When the user exits the role, the original user permissions are restored.

## Example scenario using separate development and production accounts


Imagine that your organization has multiple AWS accounts to isolate a development environment from a production environment. Users in the development account might occasionally need to access resources in the production account. For example, you might need cross-account access when you are promoting an update from the development environment to the production environment. Although you could create separate identities (and passwords) for users who work in both accounts, managing credentials for multiple accounts makes identity management difficult. In the following figure, all users are managed in the development account, but some developers require limited access to the production account. The development account has two groups: Testers and Developers, and each group has its own policy.

![\[Use a role to delegate permissions to a user in a different account\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/roles-usingroletodelegate.png)


1. In the production account, an administrator uses IAM to create the `UpdateApp` role in that account. In the role, the administrator defines a trust policy that specifies the development account as a `Principal`, meaning that authorized users from the development account can use the `UpdateApp` role. The administrator also defines a permissions policy for the role that specifies the read and write permissions to the Amazon S3 bucket named `productionapp`.

   The administrator then shares the appropriate information with anyone who needs to assume the role. That information is the account number and name of the role (for AWS console users) or the Amazon Resource Name (ARN) (for AWS CLI or AWS API access). The role ARN might look like `arn:aws:iam::123456789012:role/UpdateApp`, where the role is named `UpdateApp` and the role was created in account number 123456789012.
**Note**  
The administrator can optionally configure the role so that users who assume the role must first be authenticated using multi-factor authentication (MFA). For more information, see [Secure API access with MFA](id_credentials_mfa_configure-api-require.md). 

1. In the development account, an administrator grants members of the Developers group permission to switch to the role. This is done by granting the Developers group permission to call the AWS Security Token Service (AWS STS) `AssumeRole` API for the `UpdateApp` role. Any IAM user that belongs to the Developers group in the development account can now switch to the `UpdateApp` role in the production account. Other users who are not in the developer group do not have permission to switch to the role and therefore cannot access the S3 bucket in the production account.

1. The user requests switches to the role:
   + AWS console: The user chooses the account name on the navigation bar and chooses **Switch Role**. The user specifies the account ID (or alias) and role name. Alternatively, the user can click on a link sent in email by the administrator. The link takes the user to the **Switch Role** page with the details already filled in.
   + AWS API/AWS CLI: A user in the Developers group of the development account calls the `AssumeRole` function to obtain credentials for the `UpdateApp` role. The user specifies the ARN of the `UpdateApp` role as part of the call. If a user in the Testers group makes the same request, the request fails because Testers do not have permission to call `AssumeRole` for the `UpdateApp` role ARN.

1. AWS STS returns temporary credentials:
   + AWS console: AWS STS verifies the request with the role's trust policy to ensure that the request is from a trusted entity (which it is: the development account). After verification, AWS STS returns [temporary security credentials](https://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html) to the AWS console.
   + API/CLI: AWS STS verifies the request against the role's trust policy to ensure that the request is from a trusted entity (which it is: the Development account). After verification, AWS STS returns [temporary security credentials](https://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html) to the application.

1. The temporary credentials allow access to the AWS resource:
   + AWS console: The AWS console uses the temporary credentials on behalf of the user for all subsequent console actions, in this case, to read and write to the `productionapp` bucket. The console cannot access any other resource in the production account. When the user exits the role, the user's permissions revert to the original permissions held before switching to the role.
   + API/CLI: The application uses the temporary security credentials to update the `productionapp` bucket. With the temporary security credentials, the application can only read from and write to the `productionapp` bucket and cannot access any other resource in the Production account. The application does not have to exit the role, but instead stops using the temporary credentials and uses the original credentials in subsequent API calls.

## Additional resources


For more information, see the following:
+ [IAM tutorial: Delegate access across AWS accounts using IAM roles](tutorial_cross-account-with-roles.md)

# Access for non AWS workloads
Access for non AWS workloads

An [IAM role](id_roles.md) is an object in AWS Identity and Access Management (IAM) that is assigned [permissions](access_policies.md). When you [assume that role](id_roles_manage-assume.md) using an IAM identity or an identity from outside of AWS, it provides you with temporary security credentials for your role session. You might have workloads running in your data center or other infrastructure outside of AWS that must access your AWS resources. Instead of creating, distributing, and managing long-term access keys, you can use AWS Identity and Access Management Roles Anywhere (IAM Roles Anywhere) to authenticate your non AWS workloads. IAM Roles Anywhere uses X.509 certificates from your certificate authority (CA) to authenticate identities and securely provide access to AWS services with the temporary credentials provided by an IAM role.

**To use IAM Roles Anywhere**

1. Set up a CA using [AWS Private Certificate Authority](https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html) or use a CA from your own PKI infrastructure.

1. After you have set up a CA, you create an object in IAM Roles Anywhere called a *trust anchor*. This anchor establishes trust between IAM Roles Anywhere and your CA for authentication.

1. You can then configure your existing IAM roles, or create new roles that trust the IAM Roles Anywhere service.

1. Authenticate your non AWS workloads with IAM Roles Anywhere using the trust anchor. AWS grants the non AWS workload temporary credentials to the IAM role that has access to your AWS resources.

## Additional resources


The following resources can help you learn more about providing access to non-AWS workloads.
+ For more information about configuring IAM Roles Anywhere, see [What is AWS Identity and Access Management Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/introduction.html) in the *IAM Roles Anywhere User Guide*.
+ To learn how to set up public key infrastructure (PKI) for IAM Roles Anywhere, see [IAM Roles Anywhere with an external certificate authority](https://aws.amazon.com/blogs/) in the *AWS Security Blog*.

# Access to AWS accounts owned by third parties
Access to third-party AWS accounts

When third parties require access to your organization's AWS resources, you can use roles to delegate access to them. For example, a third party might provide a service for managing your AWS resources. With IAM roles, you can grant these third parties access to your AWS resources without sharing your AWS security credentials. Instead, the third party can access your AWS resources by assuming a role that you create in your AWS account. To learn whether principals in accounts outside of your zone of trust (trusted organization or account) have access to assume your roles, see [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html).

Third parties must provide you with the following information for you to create a role that they can assume:
+ **The third party's AWS account ID**. You specify their AWS account ID as the principal when you define the trust policy for the role.
+ **An external ID to uniquely associate with the role**. The external ID can be any identifier that is known only by you and the third party. For example, you can use an invoice ID between you and the third party, but do not use something that can be guessed, like the name or phone number of the third party. You must specify this ID when you define the trust policy for the role. The third party must provide this ID when they assume the role.
+ **The permissions that the third party requires to work with your AWS resources**. You must specify these permissions when defining the role's permission policy. This policy defines what actions they can take and what resources they can access.

After you create the role, you must provide the role's Amazon Resource Name (ARN) to the third party. They require your role's ARN in order to assume the role.

**Important**  
When you grant third parties access to your AWS resources, they can access any resource that you specify in the policy. Their use of your resources is billed to you. Ensure that you limit their use of your resources appropriately.

## External IDs for third party access


An external ID allows the user that is assuming the role to assert the circumstances in which they are operating. It also provides a way for the account owner to permit the role to be assumed only under specific circumstances. The primary function of the external ID is to address and prevent [The confused deputy problem](confused-deputy.md).

**Important**  
AWS does not treat the external ID as a secret. After you create a secret like an access key pair or a password in AWS, you cannot view them again. The external ID for a role can be seen by anyone with permission to view the role. 

## When should I use an external ID?


Use an external ID in the following situations:
+ You are an AWS account owner and you have configured a role for a third party that accesses other AWS accounts in addition to yours. You should ask the third party for an external ID that it includes when it assumes your role. Then you check for that external ID in your role's trust policy. Doing so ensures that the external party can assume your role only when it is acting on your behalf.
+ You are in the position of assuming roles on behalf of different customers like Example Corp in our previous scenario. You should assign a unique external ID to each customer and instruct them to add the external ID to their role's trust policy. You must then ensure that you always include the correct external ID in your requests to assume roles.

  You probably already have a unique identifier for each of your customers, and this unique ID is sufficient for use as an external ID. The external ID is not a special value that you need to create explicitly, or track separately, just for this purpose.

  You should always specify the external ID in your `AssumeRole` API calls. In addition when a customer gives you a role ARN, test whether you can assume the role both with and without the correct external ID. If you can assume the role without the correct external ID, don't store the customer's role ARN in your system. Wait until your customer has updated the role trust policy to require the correct external ID. In this way you help your customers to do the right thing, which helps to keep both of you protected against the confused deputy problem.

## Example scenario using an external ID


For example, let's say that you decide to hire a third-party company called Example Corp to monitor your AWS account and help optimize costs. In order to track your daily spending, Example Corp needs to access your AWS resources. Example Corp also monitors many other AWS accounts for other customers.

Do not give Example Corp access to an IAM user and its long-term credentials in your AWS account. Instead, use an IAM role and its temporary security credentials. An IAM role provides a mechanism to allow a third party to access your AWS resources without needing to share long-term credentials (such as an IAM user access key).

You can use an IAM role to establish a trusted relationship between your AWS account and the Example Corp account. After this relationship is established, a member of the Example Corp account can call the AWS Security Token Service [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API to obtain temporary security credentials. The Example Corp members can then use the credentials to access AWS resources in your account. 

**Note**  
For more information about the AssumeRole and other AWS API operations that you can call to obtain temporary security credentials, see [Compare AWS STS credentials](id_credentials_sts-comparison.md).

Here's a more detailed breakdown of this scenario:

1. You hire Example Corp, so they create a unique customer identifier for you. They provide you with this unique customer ID and their AWS account number. You need this information to create an IAM role in the next step. 
**Note**  
Example Corp can use any string value they want for the ExternalId, as long as it is unique for each customer. It can be a customer account number or even a random string of characters, as long as no two customers have the same value. It is not intended to be a 'secret'. Example Corp must provide the ExternalId value to each customer. What is crucial is that it must be generated by Example Corp and ***not*** their customers to ensure each external ID is unique.

1. You sign in to AWS and create an IAM role that gives Example Corp access to your resources. Like any IAM role, the role has two policies, a permission policy and a trust policy. The role's trust policy specifies who can assume the role. In our sample scenario, the policy specifies the AWS account number of Example Corp as the `Principal`. This allows identities from that account to assume the role. In addition, you add a `[Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition)` element to the trust policy. This `Condition` tests the `ExternalId` context key to ensure that it matches the unique customer ID from Example Corp. For example:

   ```
       "Principal": {"AWS": "Example Corp's AWS account ID"},
       "Condition": {"StringEquals": {"sts:ExternalId": "Unique ID Assigned by Example Corp"}}
   ```

1. The permission policy for the role specifies what the role allows someone to do. For example, you could specify that the role allows someone to manage only your Amazon EC2 and Amazon RDS resources but not your IAM users or groups. In our sample scenario, you use the permission policy to give Example Corp read-only access to all of the resources in your account.

1. After you create the role, you provide the Amazon Resource Name (ARN) of the role to Example Corp.

1. When Example Corp needs to access your AWS resources, someone from the company calls the AWS `sts:AssumeRole` API. The call includes the ARN of the role to assume and the ExternalId parameter that corresponds to their customer ID.

If the request comes from someone using Example Corp's AWS account, and if the role ARN and the external ID are correct, the request succeeds. It then provides temporary security credentials that Example Corp can use to access the AWS resources that your role allows.

In other words, when a role policy includes an external ID, anyone who wants to assume the role must be a principal in the role and must include the correct external ID.

## Key points for external IDs

+ In a multi-tenant environment where you support multiple customers with different AWS accounts, we recommend using one external ID per AWS account. This ID should be a random string generated by the third party.
+ To require that the third party provides an external ID when assuming a role, update the role's trust policy with the external ID of your choice.
+ To provide an external ID when you assume a role, use the AWS CLI or AWS API to assume that role. For more information, see the STS [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation, or the STS [assume-role](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) CLI operation.
+ The `ExternalId` value must have a minimum of 2 characters and a maximum of 1,224 characters. The value must be alphanumeric without white space. It can also include the following symbols: plus (\$1), equal (=), comma (,), period (.), at (@), colon (:), forward slash (/), and hyphen (-).

## Additional resources


The following resources can help you learn more about providing access to AWS accounts owned by third parties.
+ To learn how to allow others to perform actions in your AWS account, see [Create a role using custom trust policies](id_roles_create_for-custom.md).
+ To learn how to grant permission to switch to a role, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md)
+ To learn how to create and provide trusted users with temporary security credentials, [Permissions for temporary security credentials](id_credentials_temp_control-access.md).

# Access to an AWS service
Access to AWS services

Many AWS services require that you use roles to control what that service can access. A role that a service assumes to perform actions on your behalf is called a [service role](id_roles.md#iam-term-service-role). When a role serves a specialized purpose for a service, it can be categorized as a [service-linked role](id_roles.md#iam-term-service-linked-role). See the [AWS documentation](https://docs.aws.amazon.com/) for each service to see if it uses roles and to learn how to assign a role for the service to use.

For details about creating a role to delegate access to a service offered by AWS, see [Create a role to delegate permissions to an AWS service](id_roles_create_for-service.md).

# Access to externally authenticated users (identity federation)
Access through identity federation

Your users might already have identities outside of AWS, such as in your corporate directory. If those users need to work with AWS resources (or work with applications that access those resources), then those users also need AWS security credentials. You can use an IAM role to specify permissions for users whose identity is federated from your organization or a third-party identity provider (IdP).

**Note**  
As a security best practice, we recommend you manage user access in [IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/what-is.html) with identity federation instead of creating IAM users. For information about specific situations where an IAM user is required, see [When to create an IAM user (instead of a role)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_which-to-choose).

## Federating users of a mobile or web-based app with Amazon Cognito


If you create a mobile or web-based app that accesses AWS resources, the app needs security credentials in order to make programmatic requests to AWS. For most mobile application scenarios, we recommend that you use [Amazon Cognito](https://aws.amazon.com/cognito/). You can use this service with the [AWS Mobile SDK for iOS](https://aws.amazon.com/sdkforios/) and the [AWS Mobile SDK for Android and Fire OS](https://aws.amazon.com/sdkforandroid/) to create unique identities for users and authenticate them for secure access to your AWS resources. Amazon Cognito supports the same identity providers as those listed in the next section, and it also supports [developer authenticated identities](https://aws.amazon.com/blogs/mobile/amazon-cognito-announcing-developer-authenticated-identities) and unauthenticated (guest) access. Amazon Cognito also provides API operations for synchronizing user data so that it is preserved as users move between devices. For more information, see [Amazon Cognito for mobile apps](id_federation_common_scenarios.md#id_roles_providers_oidc_cognito). 

## Federating users with public identity service providers or OpenID Connect


Whenever possible, use Amazon Cognito for mobile and web-based application scenarios. Amazon Cognito does most of the behind-the-scenes work with public identity provider services for you. It works with the same third-party services and also supports anonymous sign-ins. However, for more advanced scenarios, you can work directly with a third-party service like Login with Amazon, Facebook, Google, or any IdP that is compatible with OpenID Connect (OIDC). For more information about using OIDC federation using one of these services, see [OIDC federation](id_roles_providers_oidc.md).

## Federating users with SAML 2.0


If your organization already uses an identity provider software package that supports SAML 2.0 (Security Assertion Markup Language 2.0), you can create trust between your organization as an identity provider (IdP) and AWS as the service provider. You can then use SAML to provide your users with federated single-sign on (SSO) to the AWS Management Console or federated access to call AWS API operations. For example, if your company uses Microsoft Active Directory and Active Directory Federation Services, then you can federate using SAML 2.0. For more information about federating users with SAML 2.0, see [SAML 2.0 federation](id_roles_providers_saml.md).

## Federating users by creating a custom identity broker application


If your identity store is not compatible with SAML 2.0, then you can build a custom identity broker application to perform a similar function. The broker application authenticates users, requests temporary credentials for users from AWS, and then provides them to the user to access AWS resources. 

For example, Example Corp. has many employees who need to run internal applications that access the company's AWS resources. The employees already have identities in the company identity and authentication system, and Example Corp. doesn't want to create a separate IAM user for each company employee.

Bob is a developer at Example Corp. To enable Example Corp. internal applications to access the company's AWS resources, Bob develops a custom identity broker application. The application verifies that employees are signed into the existing Example Corp. identity and authentication system, which might use LDAP, Active Directory, or another system. The identity broker application then obtains temporary security credentials for the employees. This scenario is similar to the previous one (a mobile app that uses a custom authentication system), except that the applications that need access to AWS resources all run within the corporate network, and the company has an existing authentication system.

To get temporary security credentials, the identity broker application calls either `AssumeRole` or `GetFederationToken` to obtain temporary security credentials, depending on how Bob wants to manage the policies for users and when the temporary credentials should expire. (For more information about the differences between these API operations, see [Temporary security credentials in IAM](id_credentials_temp.md) and [Permissions for temporary security credentials](id_credentials_temp_control-access.md).) The call returns temporary security credentials consisting of an AWS access key ID, a secret access key, and a session token. The identity broker application makes these temporary security credentials available to the internal company application. The app can then use the temporary credentials to make calls to AWS directly. The app caches the credentials until they expire, and then requests a new set of temporary credentials. The following figure illustrates this scenario.

![\[Sample workflow using a custom identity broker application\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/enterprise-authentication-with-identity-broker-application.diagram.png)


This scenario has the following attributes:
+ The identity broker application has permissions to access IAM's token service (STS) API to create temporary security credentials.
+ The identity broker application is able to verify that employees are authenticated within the existing authentication system.
+ Users are able to get a temporary URL that gives them access to the AWS Management Console (which is referred to as single sign-on).

For information about creating temporary security credentials, see [Compare AWS STS credentials](id_credentials_sts-comparison.md). For more information about SAML federated principals getting access to the AWS Management Console, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md).

# IAM role creation
Role creation

To create a role, you can use the AWS Management Console, the AWS CLI, the Tools for Windows PowerShell, or the IAM API.

If you use the AWS Management Console, a wizard guides you through the steps for creating a role. The wizard has slightly different steps depending on whether you're creating a role for an AWS service, for an AWS account, or for a SAML or OIDC federated principal.

**Roles for IAM users**  
Create this role to delegate permissions within your AWS account or to roles defined in other AWS accounts that you own. A user in one account can switch to a role in the same or a different account. While using the role, the user can perform only the actions and access only the resources permitted by the role; their original user permissions are suspended. When the user exits the role, the original user permissions are restored.

For more information, see [Create a role to give permissions to an IAM user](id_roles_create_for-user.md).

For more information about creating roles for cross account access, see [Create a role using custom trust policies](id_roles_create_for-custom.md).

**Roles for AWS services**  
Create this role to delegate permissions to a service that can perform actions on your behalf. A [service role](id_roles.md#iam-term-service-role) that you pass to a service must have an IAM policy with the permissions that allow the service to perform actions associated with that service. Different permissions are required for each AWS service.

For more information about creating service roles, see [Create a role to delegate permissions to an AWS service](id_roles_create_for-service.md).

For more information about creating service-linked roles, see [Create a service-linked role](id_roles_create-service-linked-role.md).

**Roles for identity federation**  
Create this role to delegate permissions to users that already have identities outside of AWS. When you use an identity provider, you don't have to create custom sign-in code or manage your own user identities. Your external users sign in through an IdP, and you can give those external identities permissions to use AWS resources in your account. Identity providers help keep your AWS account secure because you don't have to distribute or embed long-term security credentials, such as access keys, in your application.

For more information, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md).

# Create a role to give permissions to an IAM user
Create a role for an IAM user

You can use IAM roles to provide access to your AWS resources. With IAM roles, you can establish trust relationships between your *trusting* account and other AWS *trusted* accounts. The trusting account owns the resource to be accessed and the trusted account contains the users who need access to the resource. However, it is possible for another account to own a resource in your account. For example, the trusting account might allow the trusted account to create new resources, such as creating new objects in an Amazon S3 bucket. In that case, the account that creates the resource owns the resource and controls who can access that resource.

After you create the trust relationship, an IAM user or an application from the trusted account can use the AWS Security Token Service (AWS STS) [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation. This operation provides temporary security credentials that enable access to AWS resources in your account.

The accounts can both be controlled by you, or the account with the users can be controlled by a third party. If the other account with the users is an AWS account that you do not control, then you can use the `externalId` attribute. The external ID can be any word or number that is agreed upon between you and the administrator of the third-party account. This option automatically adds a condition to the trust policy that allows the user to assume the role only if the request includes the correct `sts:ExternalID`. For more information, see [Access to AWS accounts owned by third parties](id_roles_common-scenarios_third-party.md).

For information about how to use roles to delegate permissions, see [Roles terms and concepts](id_roles.md#id_roles_terms-and-concepts). For information about using a service role to allow services to access resources in your account, see [Create a role to delegate permissions to an AWS service](id_roles_create_for-service.md).

## Creating an IAM role (console)


You can use the AWS Management Console to create a role that an IAM user can assume. For example, assume that your organization has multiple AWS accounts to isolate a development environment from a production environment. For high-level information about creating a role that allows users in the development account to access resources in the production account, see [Example scenario using separate development and production accounts](id_roles_common-scenarios_aws-accounts.md#id_roles_common-scenarios_aws-accounts-example).

**Minimum permissions**  
To perform the following steps, you must have at least the following IAM permissions:  
`access-analyzer:ValidatePolicy`
`iam:AttachRolePolicy`
`iam:CreatePolicy`
`iam:CreateRole`
`iam:GetAccountSummary`
`iam:GetPolicy`
`iam:GetPolicyVersion`
`iam:GetRole`
`iam:ListAccountAliases`
`iam:ListAttachedRolePolicies`
`iam:ListOpenIDConnectProviders`
`iam:ListPolicies`
`iam:ListRolePolicies`
`iam:ListRoles`
`iam:ListRoleTags`
`iam:ListSAMLProviders`

------
#### [ Console ]

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 console, choose **Roles** and then choose **Create role**.

1. Choose **AWS account** role type.

1. To create a role for your account, choose **This account**. To create a role for another account, choose **Another AWS account** and enter the **Account ID** to which you want to grant access to your resources.

   The administrator of the specified account can grant permission to assume this role to any IAM user in that account. To do this, the administrator attaches a policy to the user or a group that grants permission for the `sts:AssumeRole` action. That policy must specify the role's ARN as the `Resource`. 

1. If you are granting permissions to users from an account that you do not control, and the users will assume this role programmatically, select **Require external ID**. The external ID can be any word or number that is agreed upon between you and the administrator of the third party account. This option automatically adds a condition to the trust policy that allows the user to assume the role only if the request includes the correct `sts:ExternalID`. For more information, see [Access to AWS accounts owned by third parties](id_roles_common-scenarios_third-party.md).
**Important**  
Choosing this option restricts access to the role only through the AWS CLI, Tools for Windows PowerShell, or the AWS API. This is because you cannot use the AWS console to switch to a role that has an `externalId` condition in its trust policy. However, you can create this kind of access programmatically by writing a script or an application using the relevant SDK. For more information and a sample script, see [How to Enable Cross-Account Access to the AWS Management Console](https://aws.amazon.com/blogs/security/how-to-enable-cross-account-access-to-the-aws-management-console) in the AWS Security Blog.

1. If you want to restrict the role to users who sign in with multi-factor authentication (MFA), select **Require MFA**. This adds a condition to the role's trust policy that checks for an MFA sign-in. A user who wants to assume the role must sign in with a temporary one-time password from a configured MFA device. Users without MFA authentication cannot assume the role. For more information about MFA, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md)

1. Choose **Next**.

1. IAM includes a list of the AWS managed and customer managed policies in your account. Select the policy to use for the permissions policy or choose **Create policy** to open a new browser tab and create a new policy from scratch. For more information, see [Creating IAM policies](access_policies_create-console.md#access_policies_create-start). After you create the policy, close that tab and return to your original tab. Select the checkbox next to the permissions policies that you want anyone who assumes the role to have. If you prefer, you can select no policies at this time, and then attach policies to the role later. By default, a role has no permissions.

1. (Optional) Set a [permissions boundary](access_policies_boundaries.md). This is an advanced feature. 

   Open the **Set permissions boundary** section and choose **Use a permissions boundary to control the maximum role permissions**. Select the policy to use for the permissions boundary.

1. Choose **Next**.

1. For **Role name**, enter a name for your role. Role names must be unique within your AWS account. When a role name is used in a policy or as part of an ARN, the role name is case sensitive. When a role name appears to customers in the console, such as during the sign-in process, the role name is case insensitive. Because various entities might reference the role, you can't edit the name of the role after it is created.

1. (Optional) For **Description**, enter a description for the new role.

1. Choose **Edit** in the **Step 1: Select trusted entities** or **Step 2: Add permissions** sections to edit the use cases and permissions for the role. You will be returned to previous pages to make the edits.

1. (Optional) Add metadata to the role by attaching tags as key–value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.
**Important**  
Remember that this is only the first half of the configuration required. You must also give individual users in the trusted account permissions to switch to the role in the console, or assume the role programmatically. For more information about this step, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

------

## Creating an IAM role (AWS CLI)


Creating a role from the AWS CLI involves multiple steps. When you use the console to create a role, many of the steps are done for you, but with the AWS CLI you must explicitly perform each step yourself. You must create the role and then assign a permissions policy to the role. Optionally, you can also set the [permissions boundary](access_policies_boundaries.md) for your role.

**To create a role for cross-account access (AWS CLI)**

1. Create a role: [aws iam create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)

1. Attach a managed permissions policy to the role: [aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)

    or

   Create an inline permissions policy for the role: [aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

1. (Optional) Add custom attributes to the role by attaching tags: [aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   For more information, see [Managing tags on IAM roles (AWS CLI or AWS API)](id_tags_roles.md#id_tags_roles_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

The following example shows the first two, and most common steps for creating a cross-account role in a simple environment. This example allows any user in the `123456789012` account to assume the role and view the `example_bucket` Amazon S3 bucket. This example also assumes that you are using a client computer running Windows, and have already configured your command line interface with your account credentials and Region. For more information, see [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

In this example, include the following trust policy in the first command when you create the role. This trust policy allows users in the `123456789012` account to assume the role using the `AssumeRole` operation, but only if the user provides MFA authentication using the `SerialNumber` and `TokenCode` parameters. For more information about MFA, see [AWS Multi-factor authentication in IAM](id_credentials_mfa.md).

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

****  

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

------

**Important**  
If your `Principal` element contains the ARN for a specific IAM role or user, then that ARN is transformed to a unique principal ID when the policy is saved. This helps mitigate the risk of someone escalating their permissions by removing and recreating the role or user. You don't normally see this ID in the console because there is also a reverse transformation back to the ARN when the trust policy is displayed. However, if you delete the role or user, then the principal ID appears in the console because AWS can no longer map it back to an ARN. Therefore, if you delete and recreate a user or role referenced in a trust policy's `Principal` element, you must edit the role to replace the ARN.

When you use the second command, you must attach an existing managed policy to the role. The following permissions policy allows anyone who assumes the role to perform only the `ListBucket` action on the `example_bucket` Amazon S3 bucket.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
      {
          "Effect": "Allow",
          "Action": "s3:ListBucket",
          "Resource": "arn:aws:s3:::example_bucket"
      }
  ]
}
```

------

To create this `Test-UserAccess-Role` role, you must first save the previous trust policy with the name `trustpolicyforacct123456789012.json` to the `policies` folder in your local `C:` drive. Then save the previous permissions policy as a customer managed policy in your AWS account with the name `PolicyForRole`. You can then use the following commands to create the role and attach the managed policy.

```
# Create the role and attach the trust policy file that allows users in the specified account to assume the role.
$ aws iam create-role --role-name Test-UserAccess-Role --assume-role-policy-document file://C:\policies\trustpolicyforacct123456789012.json

# Attach the permissions policy (in this example a managed policy) to the role to specify what it is allowed to do.
$ aws iam attach-role-policy --role-name Test-UserAccess-Role --policy-arn arn:aws:iam::123456789012:policy/PolicyForRole
```

**Important**  
Remember that this is only the first half of the configuration required. You must also give individual users in the trusted account permissions to switch to the role. For more information about this step, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

After you create the role and grant it permissions to perform AWS tasks or access AWS resources, any users in the `123456789012` account can assume the role. For more information, see [Switch to an IAM role (AWS CLI)](id_roles_use_switch-role-cli.md).

## Creating an IAM role (AWS API)


Creating a role from the AWS API involves multiple steps. When you use the console to create a role, many of the steps are done for you, but with the API you must explicitly perform each step yourself. You must create the role and then assign a permissions policy to the role. Optionally, you can also set the [permissions boundary](access_policies_boundaries.md) for your role.

**To create a role in code (AWS API)**

1. Create a role: [CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

   For the role's trust policy, you can specify a file location.

1. Attach a managed permission policy to the role: [AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

   or

   Create an inline permission policy for the role: [PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)
**Important**  
Remember that this is only the first half of the configuration required. You must also give individual users in the trusted account permissions to switch to the role. For more information about this step, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. (Optional) Add custom attributes to the user by attaching tags: [TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   For more information, see [Managing tags on IAM users (AWS CLI or AWS API)](id_tags_users.md#id_tags_users_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

After you create the role and grant it permissions to perform AWS tasks or access AWS resources, you must grant permissions to users in the account to allow them to assume the role. For more information about assuming a role, see [Switch to an IAM role (AWS API)](id_roles_use_switch-role-api.md).

## Creating an IAM role (AWS CloudFormation)


For information about creating an IAM role in AWS CloudFormation, see the [resource and property reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) and [examples](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#aws-resource-iam-role--examples) in the *AWS CloudFormation User Guide*.

For more information about IAM templates in AWS CloudFormation, see [AWS Identity and Access Management template snippets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-iam.html) in the *AWS CloudFormation User Guide*.

# Create a role to delegate permissions to an AWS service
Create a role for an AWS service

Many AWS services require that you use roles to allow the service to access resources in other services on your behalf. A role that a service assumes to perform actions on your behalf is called a [service role](id_roles.md#iam-term-service-role). When a role serves a specialized purpose for a service, it is categorized as a [service-linked role](id_roles.md#iam-term-service-linked-role). To see what services support using service-linked roles, or whether a service supports any form of temporary credentials, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md). To learn how an individual service uses roles, choose the service name in the table to view the documentation for that service.

When setting the `PassRole` permission, you should make sure that a user doesn’t pass a role where the role has more permissions than you want the user to have. For example, Alice might not be allowed to perform any Amazon S3 actions. If Alice could pass a role to a service that allows Amazon S3 actions, the service could perform Amazon S3 actions on behalf of Alice when executing the job.

For information about how roles help you to delegate permissions, see [Roles terms and concepts](id_roles.md#id_roles_terms-and-concepts).

## Service role permissions


You must configure permissions to allow an IAM entity (user or role) to create or edit a service role.

**Note**  
The ARN for a service-linked role includes a service principal, which is indicated in the following policies as `SERVICE-NAME.amazonaws.com`. Do not try to guess the service principal, because it is case-sensitive and the format can vary across AWS services. To view the service principal for a service, see its service-linked role documentation.

**To allow an IAM entity to create a specific service role**

Add the following policy to the IAM entity that needs to create the service role. This policy allows you to create a service role for the specified service and with a specific name. You can then attach managed or inline policies to that role. 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:CreateRole",
                "iam:PutRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
        }
    ]
}
```

------

**To allow an IAM entity to create any service role**

AWS recommends that you allow only administrative users to create any service role. A person with permissions to create a role and attach any policy can escalate their own permissions. Instead, create a policy that allows them to create only the roles that they need or have an administrator create the service role on their behalf.

To attach a policy that allows an administrator to access your entire AWS account, use the [AdministratorAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/AdministratorAccess) AWS managed policy.

**To allow an IAM entity to edit a service role**

Add the following policy to the IAM entity that needs to edit the service role.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "EditSpecificServiceRole",
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:DeleteRolePolicy",
                "iam:DetachRolePolicy",
                "iam:GetRole",
                "iam:GetRolePolicy",
                "iam:ListAttachedRolePolicies",
                "iam:ListRolePolicies",
                "iam:PutRolePolicy",
                "iam:UpdateRole",
                "iam:UpdateRoleDescription"
            ],
            "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
        },
        {
            "Sid": "ViewRolesAndPolicies",
            "Effect": "Allow",
            "Action": [
                "iam:GetPolicy",
                "iam:ListRoles"
            ],
            "Resource": "*"
        }
    ]
}
```

------

**To allow an IAM entity to delete a specific service role**

Add the following statement to the permissions policy for the IAM entity that needs to delete the specified service role.

```
{
    "Effect": "Allow",
    "Action": "iam:DeleteRole",
    "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
}
```

**To allow an IAM entity to delete any service role**

AWS recommends that you allow only administrative users to delete any service role. Instead, create a policy that allows them to delete only the roles that they need or have an administrator delete the service role on their behalf.

To attach a policy that allows an administrator to access your entire AWS account, use the [AdministratorAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/AdministratorAccess) AWS managed policy.

## Creating a role for an AWS service (console)


You can use the AWS Management Console to create a role for a service. Because some services support more than one service role, see the [AWS documentation](https://docs.aws.amazon.com/) for your service to see which use case to choose. You can learn how to assign the necessary trust and permissions policies to the role so that the service can assume the role on your behalf. The steps that you can use to control the permissions for your role can vary, depending on how the service defines the use cases, and whether or not you create a service-linked role.

------
#### [ Console ]

**To create a role for an AWS service (IAM console)**

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, choose **Roles**, and then choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Service or use case**, choose a service, and then choose the use case. Use cases are defined by the service to include the trust policy that the service requires.

1. Choose **Next**.

1. For **Permissions policies**, the options depend on the use case that you selected:
   + If the service defines the permissions for the role, you can't select permissions policies.
   + Select from a limited set of permission polices.
   + Select from all permission policies.
   + Select no permissions policies, create the policies after the role is created, and then attach the policies to the role.

1. (Optional) Set a [permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html). This is an advanced feature that is available for service roles, but not service-linked roles.

   1. Open the **Set permissions boundary** section, and then choose **Use a permissions boundary to control the maximum role permissions**. 

      IAM includes a list of the AWS managed and customer-managed policies in your account.

   1. Select the policy to use for the permissions boundary.

1. Choose **Next**.

1. For **Role name**, the options depend on the service:
   + If the service defines the role name, you can't edit the role name.
   + If the service defines a prefix for the role name, you can enter an optional suffix.
   + If the service doesn't define the role name, you can name the role.
**Important**  
When you name a role, note the following:  
Role names must be unique within your AWS account, and can't be made unique by case.  
For example, don't create roles named both **PRODROLE** and **prodrole**. When a role name is used in a policy or as part of an ARN, the role name is case sensitive, however when a role name appears to customers in the console, such as during the sign-in process, the role name is case insensitive.
You can't edit the name of the role after it's created because other entities might reference the role.

1. (Optional) For **Description**, enter a description for the role.

1. (Optional) To edit the use cases and permissions for the role, in the **Step 1: Select trusted entities** or **Step 2: Add permissions** sections, choose **Edit**.

1. (Optional) To help identify, organize, or search for the role, add tags as key-value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) in the *IAM User Guide*.

1. Review the role, and then choose **Create role**.

------

## Creating a role for a service (AWS CLI)


Creating a role from the AWS CLI involves multiple steps. When you use the console to create a role, many of the steps are done for you, but with the AWS CLI you must explicitly perform each step yourself. You must create the role and then assign a permissions policy to the role. If the service you are working with is Amazon EC2, then you must also create an instance profile and add the role to it. Optionally, you can also set the [permissions boundary](access_policies_boundaries.md) for your role.

**To create a role for an AWS service from the AWS CLI**

1. The following `[create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)` command creates a role named *Test-Role* and attaches a trust policy to it:

   `aws iam create-role --role-name Test-Role --assume-role-policy-document file://Test-Role-Trust-Policy.json`

1. Attach a managed permissions policy to the role: [aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html).

   For example, the following `attach-role-policy` command attaches the AWS managed policy named `ReadOnlyAccess` to the IAM role named `ReadOnlyRole`:

   `aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --role-name ReadOnlyRole`

    or

   Create an inline permissions policy for the role: [aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

   To add an inline permissions policy, see the following example:

    `aws iam put-role-policy --role-name Test-Role --policy-name ExamplePolicy --policy-document file://AdminPolicy.json`

1. (Optional) Add custom attributes to the role by attaching tags: [aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   For more information, see [Managing tags on IAM roles (AWS CLI or AWS API)](id_tags_roles.md#id_tags_roles_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

If you are going to use the role with Amazon EC2 or another AWS service that uses Amazon EC2, you must store the role in an instance profile. An instance profile is a container for a role that can be attached to an Amazon EC2 instance when launched. An instance profile can contain only one role, and that limit cannot be increased. If you create the role using the AWS Management Console, the instance profile is created for you with the same name as the role. For more information about instance profiles, see [Use instance profiles](id_roles_use_switch-role-ec2_instance-profiles.md). For information about how to launch an EC2 instance with a role, see [Controlling Access to Amazon EC2 Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html#UsingIAMrolesWithAmazonEC2Instances) in the *Amazon EC2 User Guide*.

**To create an instance profile and store the role in it (AWS CLI)**

1. Create an instance profile: [aws iam create-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html)

1. Add the role to the instance profile: [aws iam add-role-to-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html)

The AWS CLI example command set below demonstrates the first two steps for creating a role and attaching permissions. It also shows the two steps for creating an instance profile and adding the role to the profile. This example trust policy allows the Amazon EC2 service to assume the role and view the `example_bucket` Amazon S3 bucket. The example also assumes that you are running on a client computer running Windows and have already configured your command line interface with your account credentials and Region. For more information, see [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

In this example, include the following trust policy in the first command when you create the role. This trust policy allows the Amazon EC2 service to assume the role. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {"Service": "ec2.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }
}
```

------

When you use the second command, you must attach a permissions policy to the role. The following example permissions policy allows the role to perform only the `ListBucket` action on the `example_bucket` Amazon S3 bucket.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::example_bucket"
  }
}
```

------

To create this `Test-Role-for-EC2` role, you must first save the previous trust policy with the name `trustpolicyforec2.json` and the previous permissions policy with the name `permissionspolicyforec2.json` to the `policies` directory in your local `C:` drive. You can then use the following commands to create the role, attach the policy, create the instance profile, and add the role to the instance profile.

```
# Create the role and attach the trust policy that allows EC2 to assume this role.
$ aws iam create-role --role-name Test-Role-for-EC2 --assume-role-policy-document file://C:\policies\trustpolicyforec2.json

# Embed the permissions policy (in this example an inline policy) to the role to specify what it is allowed to do.
$ aws iam put-role-policy --role-name Test-Role-for-EC2 --policy-name Permissions-Policy-For-Ec2 --policy-document file://C:\policies\permissionspolicyforec2.json

# Create the instance profile required by EC2 to contain the role
$ aws iam create-instance-profile --instance-profile-name EC2-ListBucket-S3

# Finally, add the role to the instance profile
$ aws iam add-role-to-instance-profile --instance-profile-name EC2-ListBucket-S3 --role-name Test-Role-for-EC2
```

When you launch the EC2 instance, specify the instance profile name in the **Configure Instance Details** page if you use the AWS console. If you use the `aws ec2 run-instances` CLI command, specify the `--iam-instance-profile` parameter.

## Creating a role for a service (AWS API)


Creating a role from the AWS API involves multiple steps. When you use the console to create a role, many of the steps are done for you, but with the API you must explicitly perform each step yourself. You must create the role and then assign a permissions policy to the role. If the service you are working with is Amazon EC2, then you must also create an instance profile and add the role to it. Optionally, you can also set the [permissions boundary](access_policies_boundaries.md) for your role.

**To create a role for an AWS service (AWS API)**

1. Create a role: [CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

   For the role's trust policy, you can specify a file location.

1. Attach a managed permissions policy to the role: [AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

    or

   Create an inline permissions policy for the role: [PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

1. (Optional) Add custom attributes to the user by attaching tags: [TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   For more information, see [Managing tags on IAM users (AWS CLI or AWS API)](id_tags_users.md#id_tags_users_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

If you are going to use the role with Amazon EC2 or another AWS service that uses Amazon EC2, you must store the role in an instance profile. An instance profile is a container for a role. Each instance profile can contain only one role, and that limit cannot be increased. If you create the role in the AWS Management Console, the instance profile is created for you with the same name as the role. For more information about instance profiles, see [Use instance profiles](id_roles_use_switch-role-ec2_instance-profiles.md). For information about how to launch an Amazon EC2 instance with a role, see [Controlling Access to Amazon EC2 Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html#UsingIAMrolesWithAmazonEC2Instances) in the *Amazon EC2 User Guide*. 

**To create an instance profile and store the role in it (AWS API)**

1. Create an instance profile: [CreateInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html)

1. Add the role to the instance profile: [AddRoleToInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html)

# Create a service-linked role


A service-linked role is a unique type of IAM role that is linked directly to an AWS service. Service-linked roles are predefined by the service and include all the permissions that the service requires to call other AWS services on your behalf. The linked service also defines how you create, modify, and delete a service-linked role. A service might automatically create or delete the role. It might allow you to create, modify, or delete the role as part of a wizard or process in the service. Or it might require that you use IAM to create or delete the role. Regardless of the method, service-linked roles simplify the process of setting up a service because you don't have to manually add permissions for the service to complete actions on your behalf.

**Note**  
Remember that service roles are different from service-linked roles. A service role is an [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see [Create a role to delegate permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*. A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. 

The linked service defines the permissions of its service-linked roles, and unless defined otherwise, only that service can assume the roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy cannot be attached to any other IAM entity.

Before you can delete the roles, you must first delete their related resources. This helps prevent you from inadvertently removing permission to access the resources. 

**Tip**  
For information about which services support using service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-Linked Role** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

## Service-linked role permissions


You must configure permissions for an IAM entity (user or role) to allow the user or role to create or edit the service-linked role.

**Note**  
The ARN for a service-linked role includes a service principal, which is indicated in the policies below as `SERVICE-NAME.amazonaws.com`. Do not try to guess the service principal, because it is case sensitive and the format can vary across AWS services. To view the service principal for a service, see its service-linked role documentation.

**To allow an IAM entity to create a specific service-linked role**

Add the following policy to the IAM entity that needs to create the service-linked role.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*",
            "Condition": {"StringLike": {"iam:AWSServiceName": "SERVICE-NAME.amazonaws.com"}}
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*"
        }
    ]
}
```

------

**To allow an IAM entity to create any service-linked role**

Add the following statement to the permissions policy for the IAM entity that needs to create a service-linked role, or any service role that includes the needed policies. This policy statement does not allow the IAM entity to attach a policy to the role.

```
{
    "Effect": "Allow",
    "Action": "iam:CreateServiceLinkedRole",
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**To allow an IAM entity to edit the description of any service roles**

Add the following statement to the permissions policy for the IAM entity that needs to edit the description of a service-linked role, or any service role.

```
{
    "Effect": "Allow",
    "Action": "iam:UpdateRoleDescription",
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**To allow an IAM entity to delete a specific service-linked role**

Add the following statement to the permissions policy for the IAM entity that needs to delete the service-linked role.

```
{
    "Effect": "Allow",
    "Action": [
        "iam:DeleteServiceLinkedRole",
        "iam:GetServiceLinkedRoleDeletionStatus"
    ],
    "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*"
}
```

**To allow an IAM entity to delete any service-linked role**

Add the following statement to the permissions policy for the IAM entity that needs to delete a service-linked role, but not service role.

```
{
    "Effect": "Allow",
    "Action": [
        "iam:DeleteServiceLinkedRole",
        "iam:GetServiceLinkedRoleDeletionStatus"
    ],
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**To allow an IAM entity to pass an existing role to the service**

Some AWS services allow you to pass an existing role to the service, instead of creating a new service-linked role. To do this, a user must have permissions to *pass the role* to the service. Add the following statement to the permissions policy for the IAM entity that needs to pass a role. This policy statement also allows the entity to view a list of roles from which they can choose the role to pass. For more information, see [Grant a user permissions to pass a role to an AWS service](id_roles_use_passrole.md).

```
{
  "Sid": "PolicyStatementToAllowUserToListRoles",
  "Effect": "Allow",
  "Action": ["iam:ListRoles"],
  "Resource": "*"
},
{
  "Sid": "PolicyStatementToAllowUserToPassOneSpecificRole",
  "Effect": "Allow",
  "Action": [ "iam:PassRole" ],
  "Resource": "arn:aws:iam::account-id:role/my-role-for-XYZ"
}
```

## Indirect permissions with service-linked roles
Indirect permissions

The permissions granted by a service-linked role can be indirectly transferred to other users and roles. When a service-linked role is used by an AWS service, that service-linked role can use its own permissions to call other AWS services. This means that users and roles with permissions to call a service that uses a service-linked role may have indirect access to services that can be accessed by that service-linked role.

For example, when you create an Amazon RDS DB instance, [a service-linked role for RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.ServiceLinkedRoles.html) is automatically created if one does not already exist. This service-linked role allows RDS to call Amazon EC2, Amazon SNS, Amazon CloudWatch Logs, and Amazon Kinesis on your behalf. If you allow users and roles in your account to modify or create RDS databases, then they may be able to indirectly interact with Amazon EC2, Amazon SNS, Amazon CloudWatch Logs logs, and Amazon Kinesis resources by calling RDS, as RDS would use it’s service-linked role to access those resources.

### Methods to create a service-linked role


The method that you use to create a service-linked role depends on the service. In some cases, you don't need to manually create a service-linked role. For example, when you complete a specific action (such as creating a resource) in the service, the service might create the service-linked role for you. Or if you were using a service before it began supporting service-linked roles, then the service might have automatically created the role in your account. To learn more, see [A new role appeared in my AWS account](troubleshoot_roles.md#troubleshoot_roles_new-role-appeared).

In other cases, the service might support creating a service-linked role manually using the service console, API, or CLI. For information about which services support using service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-Linked Role** column. To learn whether the service supports creating the service-linked role, choose the **Yes** link to view the service-linked role documentation for that service.

If the service does not support creating the role, then you can use IAM to create the service-linked role.

**Important**  
Service-linked roles count toward your [IAM roles in an AWS account](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities) limit, but if you have reached your limit, you can still create service-linked roles in your account. Only service-linked roles can exceed the limit.

### Creating a service-linked role (console)


Before you create a service-linked role in IAM, find out whether the linked service automatically creates service-linked roles, In addition, learn whether you can create the role from the service's console, API, or CLI.<a name="create-service-linked-role-iam-console"></a>

**To create a service-linked role (console)**

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, choose **Roles**. Then, choose **Create role**.

1. Choose the **AWS Service** role type.

1. Choose the use case for your service. Use cases are defined by the service to include the trust policy required by the service. Then, choose **Next**.

1. Choose one or more permissions policies to attach to the role. Depending on the use case that you selected, the service might do any of the following:
   + Define the permissions used by the role.
   + Allow you to choose from a limited set of permissions.
   + Allow you to choose from any permissions.
   + Allow you to select no policies at this time, create the policies later, and then attach them to the role.

   Select the checkbox next to the policy that assigns the permissions that you want the role to have, and then choose **Next**. 
**Note**  
The permissions that you specify are available to any entity that uses the role. By default, a role has no permissions.

1. For **Role name**, the degree of role name customization is defined by the service. If the service defines the role's name, then this option is not editable. In other cases, the service might define a prefix for the role and let you enter an optional suffix.

   If possible, enter a role name suffix to add to the default name. This suffix helps you identify the purpose of this role. Role names must be unique within your AWS account. They are not distinguished by case. For example, you cannot create roles named both **<service-linked-role-name>\$1SAMPLE** and **<service-linked-role-name>\$1sample**. Because various entities might reference the role, you cannot edit the name of the role after it has been created.

1. (Optional) For **Description**, edit the description for the new service-linked role.

1. You cannot attach tags to service-linked roles during creation. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.

### Creating a service-linked role (AWS CLI)


Before creating a service-linked role in IAM, find out whether the linked service automatically creates service-linked roles and whether you can create the role from the service's CLI. If the service CLI is not supported, you can use IAM commands to create a service-linked role with the trust policy and inline policies that the service needs to assume the role.

**To create a service-linked role (AWS CLI)**

Run the following command:

```
aws iam [create-service-linked-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-service-linked-role.html) --aws-service-name SERVICE-NAME.amazonaws.com
```

### Creating a service-linked role (AWS API)


Before creating a service-linked role in IAM, find out whether the linked service automatically creates service-linked roles and whether you can create the role from the service's API. If the service API is not supported, you can use the AWS API to create a service-linked role with the trust policy and inline policies that the service needs to assume the role.

**To create a service-linked role (AWS API)**

Use the [CreateServiceLinkedRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceLinkedRole.html) API call. In the request, specify a service name of `SERVICE_NAME_URL.amazonaws.com`. 

For example, to create the **Lex Bots** service-linked role, use `lex.amazonaws.com`.

# Create a role for a third-party identity provider
Create a role for identity federation

You can use identity providers instead of creating IAM users in your AWS account. With an identity provider (IdP), you can manage your user identities outside of AWS and give these external user identities permissions to access AWS resources in your account. For more information about federation and identity providers, see [Identity providers and federation into AWS](id_roles_providers.md).

## Creating a role for OIDC and SAML federated principals (console)
Creating a role (console)

The procedures for creating a role depends on your choice of third party providers:
+ For OpenID Connect (OIDC), see [Create a role for OpenID Connect federation (console)](id_roles_create_for-idp_oidc.md).
+ For SAML 2.0, see [Create a role for SAML 2.0 federation (console)](id_roles_create_for-idp_saml.md).

## Creating a role for federated access (AWS CLI)


The steps to create a role for the supported identity providers (OIDC or SAML) from the AWS CLI are identical. The difference is in the contents of the trust policy that you create in the prerequisite steps. Begin by following the steps in the **Prerequisites** section for the type of provider you are using:
+ For an OIDC provider, see [Prerequisites for creating a role for OIDC](id_roles_create_for-idp_oidc.md#idp_oidc_Prerequisites).
+ For a SAML provider, see [Prerequisites for creating a role for SAML](id_roles_create_for-idp_saml.md#idp_saml_Prerequisites).

Creating a role from the AWS CLI involves multiple steps. When you use the console to create a role, many of the steps are done for you, but with the AWS CLI you must explicitly perform each step yourself. You must create the role and then assign a permissions policy to the role. Optionally, you can also set the [permissions boundary](access_policies_boundaries.md) for your role.

**To create a role (AWS CLI)**

1. Create a role: [aws iam create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)

1. Attach a permissions policy to the role: [aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)

    or

   Create an inline permissions policy for the role: [aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

1. (Optional) Add custom attributes to the role by attaching tags: [aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   For more information, see [Managing tags on IAM roles (AWS CLI or AWS API)](id_tags_roles.md#id_tags_roles_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

The following example shows the first two, and most common, steps for creating an identity provider role in a simple environment. This example allows any user in the `123456789012` account to assume the role and view the `example_bucket` Amazon S3 bucket. This example also assumes that you are running the AWS CLI on a computer running Windows, and have already configured the AWS CLI with your credentials. For more information, see [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

The following example trust policy is designed for a mobile app if the user signs in using Amazon Cognito. In this example, *us-east:12345678-ffff-ffff-ffff-123456* represents the identity pool ID assigned by Amazon Cognito.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Sid": "RoleForCognito",
        "Effect": "Allow",
        "Principal": {"Federated": "cognito-identity.amazonaws.com"},
        "Action": "sts:AssumeRoleWithWebIdentity",
        "Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}
    }
}
```

------

The following permissions policy allows anyone who assumes the role to perform only the `ListBucket` action on the `example_bucket` Amazon S3 bucket.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::example_bucket"
  }
}
```

------

To create this `Test-Cognito-Role` role, you must first save the previous trust policy with the name `trustpolicyforcognitofederation.json` and the previous permissions policy with the name `permspolicyforcognitofederation.json` to the `policies` folder in your local `C:` drive. You can then use the following commands to create the role and attach the inline policy.

```
# Create the role and attach the trust policy that enables users in an account to assume the role.
$ aws iam create-role --role-name Test-Cognito-Role --assume-role-policy-document file://C:\policies\trustpolicyforcognitofederation.json

# Attach the permissions policy to the role to specify what it is allowed to do.
aws iam put-role-policy --role-name Test-Cognito-Role --policy-name Perms-Policy-For-CognitoFederation --policy-document file://C:\policies\permspolicyforcognitofederation.json
```

## Creating a role for federated access (AWS API)


The steps to create a role for the supported identity providers (OIDC or SAML) from the AWS CLI are identical. The difference is in the contents of the trust policy that you create in the prerequisite steps. Begin by following the steps in the **Prerequisites** section for the type of provider you are using:
+ For an OIDC provider, see [Prerequisites for creating a role for OIDC](id_roles_create_for-idp_oidc.md#idp_oidc_Prerequisites).
+ For a SAML provider, see [Prerequisites for creating a role for SAML](id_roles_create_for-idp_saml.md#idp_saml_Prerequisites).

**To create a role (AWS API)**

1. Create a role: [CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

1. Attach a permissions policy to the role:[AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

    or

   Create an inline permissions policy for the role: [PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

1. (Optional) Add custom attributes to the user by attaching tags: [TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   For more information, see [Managing tags on IAM users (AWS CLI or AWS API)](id_tags_users.md#id_tags_users_procs-cli-api).

1. (Optional) Set the [permissions boundary](access_policies_boundaries.md) for the role: [PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   A permissions boundary controls the maximum permissions that a role can have. Permissions boundaries are an advanced AWS feature.

# Create a role for OpenID Connect federation (console)
Create a role for OIDC federation

You can use OpenID Connect (OIDC) federated identity providers instead of creating AWS Identity and Access Management users in your AWS account. With an identity provider (IdP), you can manage your user identities outside of AWS and give these external user identities permissions to access AWS resources in your account. For more information about federation and IdPs, see [Identity providers and federation into AWS](id_roles_providers.md).

## Prerequisites for creating a role for OIDC


Before you can create a role for OIDC federation, you must first complete the following prerequisite steps.<a name="oidc-prereqs"></a>

**To prepare to create a role for OIDC federation**

1. Sign up with one or more services offering federated OIDC identity. If you are creating an app that needs access to your AWS resources, you also configure your app with the provider information. When you do, the provider gives you an application or audience ID that is unique to your app. (Different providers use different terminology for this process. This guide uses the term *configure* for the process of identifying your app with the provider.) You can configure multiple apps with each provider, or multiple providers with a single app. View information about using the identity providers as follows:
   + [Login with Amazon Developer Center](https://login.amazon.com/)
   + [Add Facebook Login to Your App or Website](https://developers.facebook.com/docs/facebook-login/v2.1) on the Facebook developers site.
   + [Using OAuth 2.0 for Login (OpenID Connect)](https://developers.google.com/accounts/docs/OAuth2Login) on the Google developers site.

1. <a name="idpoidcstep2"></a>After you receive the required information from the IdP, create an IdP in IAM. For more information, see [Create an OpenID Connect (OIDC) identity provider in IAM](id_roles_providers_create_oidc.md).
**Important**  
If you are using an OIDC IdP from Google, Facebook, or Amazon Cognito, don't create a separate IAM IdP in the AWS Management Console. These OIDC identity providers are already built into AWS and are available for you to use. Skip this step and create new roles using your IdP in the following step.

1. Prepare the policies for the role that the IdP-authenticated users will assume. As with any role, a role for a mobile app includes two policies. One is the trust policy that specifies who can assume the role. The other is the permissions policy that specifies the AWS actions and resources that the mobile app is allowed or denied access to.

   For web IdPs, we recommend that you use [Amazon Cognito](https://aws.amazon.com/cognito/) to manage identities. In this case, use a trust policy similar to this example.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"Federated": "cognito-identity.amazonaws.com"},
           "Action": "sts:AssumeRoleWithWebIdentity",
           "Condition": {
               "StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east-2:12345678-abcd-abcd-abcd-123456"},
               "ForAnyValue:StringLike": {"cognito-identity.amazonaws.com:amr": "unauthenticated"}
           }
       }
   }
   ```

------

   Replace `us-east-2:12345678-abcd-abcd-abcd-123456` with the identity pool ID that Amazon Cognito assigns to you.

   If you manually configure an OIDC IdP, when you create the trust policy, you must use three values that ensure that only your app can assume the role:
   + For the `Action` element, use the `sts:AssumeRoleWithWebIdentity` action.
   + For the `Principal` element, use the string `{"Federated":providerUrl/providerArn}`.
     + For some common OIDC IdPs, the `providerUrl` is a URL. The following examples include methods to specify the principal for some common IdPs:

       `"Principal":{"Federated":"cognito-identity.amazonaws.com"}`

       `"Principal":{"Federated":"www.amazon.com"}`

       `"Principal":{"Federated":"graph.facebook.com"}`

       `"Principal":{"Federated":"accounts.google.com"}`
     + For other OIDC providers, use the Amazon Resource Name (ARN) of the OIDC IdP that you created in [Step 2](#idpoidcstep2), such as the following example:

       `"Principal":{"Federated":"arn:aws:iam::123456789012:oidc-provider/server.example.com"}`
   + For the `Condition` element, use a `StringEquals` condition to limit permissions. Test the identity pool ID for Amazon Cognito) or the app ID for other providers. The identity pool ID should match the app ID that you received when you configured the app with the IdP. This match between the IDs ensures that the request comes from your app.
**Note**  
IAM roles for Amazon Cognito identity pools trust the service principal `cognito-identity.amazonaws.com` to assume the role. Roles of this type must contain at least one condition key to limit the principals who can assume the role.  
Additional considerations apply to Amazon Cognito identity pools that assume [cross-account IAM roles](access_policies-cross-account-resource-access.md). The trust policies of these roles must accept the `cognito-identity.amazonaws.com` service principal and must contain the `aud` condition key to restrict role assumption to users from your intended identity pools. A policy that trusts Amazon Cognito identity pools without this condition creates a risk that a user from an unintended identity pool can assume the role. For more information, see [ Trust policies for IAM roles in Basic (Classic) authentication ](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#trust-policies) in the *Amazon Cognito Developer Guide*.

     Create a condition element similar to one of the following examples, depending on the IdP that you are using: 

     `"Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}`

     `"Condition": {"StringEquals": {"www.amazon.com:app_id": "amzn1.application-oa2-123456"}}`

     `"Condition": {"StringEquals": {"graph.facebook.com:app_id": "111222333444555"}}`

     `"Condition": {"StringEquals": {"accounts.google.com:aud": "66677788899900pro0"}}`

     For OIDC providers, use the fully qualified URL of the OIDC IdP with the `aud` context key, such as the following example: 

     `"Condition": {"StringEquals": {"server.example.com:aud": "appid_from_oidc_idp"}}`
**Note**  
The values for the principal in the trust policy for the role are specific to an IdP. A role for OIDC can specify only one principal. Therefore, if the mobile app allows users to sign in from more than one IdP, create a separate role for each IdP that you want to support. Create separate trust policies for each IdP.

   If a user uses a mobile app to sign in from Login with Amazon, the following example trust policy would apply. In the example, *amzn1.application-oa2-123456* represents the app ID that Amazon assigns when you configured the app using Login with Amazon.

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

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForLoginWithAmazon",
             "Effect": "Allow",
             "Principal": {"Federated": "www.amazon.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"www.amazon.com:app_id": "amzn1.application-oa2-123456"}}
         }]
     }
   ```

------

   If a user uses a mobile app to sign in from Facebook, the following example trust policy would apply. In this example, *111222333444555* represents the app ID that Facebook assigns.

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

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForFacebook",
             "Effect": "Allow",
             "Principal": {"Federated": "graph.facebook.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"graph.facebook.com:app_id": "111222333444555"}}
         }]
     }
   ```

------

   If a user uses a mobile app to sign in from Google, the following example trust policy would apply. In this example, *666777888999000* represents the app ID that Google assigns.

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

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForGoogle",
             "Effect": "Allow",
             "Principal": {"Federated": "accounts.google.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"accounts.google.com:aud": "666777888999000"}}
         }]
     }
   ```

------

   If a user uses a mobile app to sign in from Amazon Cognito, the following example trust policy would apply. In this example, *us-east:12345678-ffff-ffff-ffff-123456* represents the identity pool ID that Amazon Cognito assigns.

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

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForCognito",
             "Effect": "Allow",
             "Principal": {"Federated": "cognito-identity.amazonaws.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}
         }]
     }
   ```

------

## Creating a role for OIDC


After you complete the prerequisites, you can create the role in IAM. For recognized shared OpenID Connect (OIDC) identity providers (IdPs), IAM requires explicit evaluation of specific claims in JSON Web Tokens (JWTs) known as *identity-provider controls*. For more information about which OIDC IdPs have *identity-provider controls*, see [Identity-provider controls for shared OIDC providers](id_roles_providers_oidc_secure-by-default.md).

The following procedure describes how to create the role for OIDC federation in the AWS Management Console. To create a role from the AWS CLI or AWS API, see the procedures at [Create a role for a third-party identity provider](id_roles_create_for-idp.md).

**Important**  
If you use Amazon Cognito, use the Amazon Cognito console to set up the roles. Otherwise, use the IAM console to create a role for OIDC federation.

**To create an IAM role for OIDC federation**

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, choose **Roles** and then choose **Create role**.

1. Choose **Web identity** as the trusted entity type and select **Next**.

1. For **Identity provider**, choose the IdP for your role: 
   + If you want to create a role for an individual web IdP, choose **Login with Amazon**, **Facebook**, or **Google**. 
**Note**  
You must create a separate role for each IdP that you want to support.
   + If you want to create an advanced scenario role for Amazon Cognito, choose **Amazon Cognito**. 
**Note**  
You must manually create a role to use with Amazon Cognito only when you work on an advanced scenario. Otherwise, Amazon Cognito can create roles for you. For more information about Amazon Cognito, see [Identity pools (federated identities) external identity providers](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) in the *Amazon Cognito Developer Guide*. 
   + If you want to create a role for GitHub Actions, you must start by adding the GitHub OIDC provider to IAM. After you've added the GitHub OIDC provider to IAM, choose **token.actions.githubusercontent.com**. 
**Note**  
For information about how to configure AWS to trust GitHub's OIDC provider as a federated identity, see [GitHub Docs - Configuring OpenID Connect in Amazon Web Services](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services). For information about best practices for limiting access for roles associated with the IAM IdP for GitHub, see [Configuring a role for GitHub OIDC identity provider](#idp_oidc_Create_GitHub) on this page.
   + If you want to create a role for HashiCorp Cloud Platform (HCP) Terraform, you must start by adding the Terraform OIDC provider to IAM. After you've added the Terraform OIDC provider to IAM, choose **app.terraform.io**. 
**Important**  
IAM roles for HashiCorp Cloud Platform (HCP) Terraform OIDC provider must evaluate the IAM condition key, `app.terraform.io:sub`, in the role trust policy. This condition key limits which HCP Terraform organizations, projects, workspaces, or run phases are able to assume the role. Without this condition key, your trust policy grants access to your role and AWS resources by identities outside of your organization, which does not align with the principle of least privilege.   
If you set or modify a role trust policy for a role associated with the HCP Terraform OIDC provider in your AWS account, but do not evaluate IAM condition key `app.terraform.io:sub`, you will receive an error. Additionally, AWS STS will deny authorization requests if your role trust policy doesn't evaluate this condition key.

1. The requested information varies based on the OIDC provider you choose.
   + Enter the identifier for your application. The label of the identifier changes based on the provider you choose:
     + If you want to create a role for Login with Amazon, enter the app ID into the **Application ID** box.
     + If you want to create a role for Facebook, enter the app ID into the **Application ID** box.
     + If you want to create a role for Google, enter the audience name into the **Audience** box.
     + If you want to create a role for Amazon Cognito, enter the ID of the identity pool that you have created for your Amazon Cognito applications into the **Identity Pool ID** box.
   + If you want to create a role for GitHub Actions, enter the following details:
     + For **Audience**, choose `sts.amazonaws.com`.
     + For **GitHub organization**, enter the GitHub organization name. The GitHub organization name is required and must be alphanumeric including dashes (-). You can't use wildcard characters (\$1 and ?) in the GitHub organization name.
     + (Optional) For **GitHub repository**, enter the GitHub repository name. If you don’t specify a value, it defaults to a wildcard (`*`).
     + (Optional) For **GitHub branch**, enter the GitHub branch name. If you don’t specify a value, it defaults to a wildcard (`*`).
   + If you want to create a role for HashiCorp Cloud Platform (HCP) Terraform, enter the following details:
     + For **Audience**, choose `aws.workload.identity`.
     + For **Organization**, enter the organization name. You can specify a wildcard character (`*`) for all organizations.
     + For **Project**, enter the project name. You can specify a wildcard character (`*`) for all projects.
     + For **Workspace**, enter the workspace name. You can specify a wildcard character (`*`) for all workspaces.
     + For **Run Phase**, enter the run phase name. You can specify a wildcard character (`*`) for all run phases.

1. (Optional) For **Condition (optional)**, choose **Add Condition** to create additional conditions that must be met before users of your application can use the permissions that the role grants. For example, you can add a condition that grants access to AWS resources only for a specific IAM user ID. You can also add conditions to the trust policy after the role is created. For more information, see [Update a role trust policy](id_roles_update-role-trust-policy.md).

1. Review your OIDC information and then choose **Next**.

1. IAM includes a list of the AWS managed and customer managed policies in your account. Select the policy to use for the permissions policy, or choose **Create policy** to open a new browser tab and create a new policy from scratch. For more information, see [Creating IAM policies](access_policies_create-console.md#access_policies_create-start). After you create the policy, close that tab and return to your original tab. Select the checkbox next to the permissions policies that you want OIDC users to have. If you prefer, you can select no policies at this time, and then attach policies to the role later. By default, a role has no permissions.

1. (Optional) Set a [permissions boundary](access_policies_boundaries.md). This is an advanced feature.

   Open the **Permissions boundary** section and choose **Use a permissions boundary to control the maximum role permissions**. Select the policy to use for the permissions boundary.

1. Choose **Next**.

1. For **Role name**, enter a role name. Role names must be unique within your AWS account. They are not case dependent. For example, you can't create roles named both **PRODROLE** and **prodrole**. Because other AWS resources might reference the role, you can't edit the name of the role after you create it.

1. (Optional) For **Description**, enter a description for the new role.

1. To edit the use cases and permissions for the role, choose **Edit** in the **Step 1: Select trusted entities** or **Step 2: Add permissions** sections. 

1. (Optional) To add metadata to the role, attach tags as key–value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.

## Configuring a role for GitHub OIDC identity provider


If you use GitHub as an OpenID Connect (OIDC) identity provider (IdP), best practice is to limit the entities that can assume the role associated with the IAM IdP. When you include a condition statement in the trust policy, you can limit the role to a specific GitHub organization, repository, or branch. You can use the condition key `token.actions.githubusercontent.com:sub` with string condition operators to limit access. We recommend that you limit the condition to a specific set of repositories or branches within your GitHub organization. For information about how to configure AWS to trust GitHub's OIDC as a federated identity, see [GitHub Docs - Configuring OpenID Connect in Amazon Web Services](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services). 

If you use GitHub environments in action workflows or in OIDC policies, we strongly recommend adding protection rules to the environment for additional security. Use deployment branches and tags to restrict which branches and tags can deploy to the environment. For more information on configuring environments with protection rules, see [Deployment branches and tags](https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-branches-and-tags) in GitHub's *Using environments for deployment* article.

When GitHub's OIDC IdP is the trusted Principal for your role, IAM checks the role trust policy condition to verify that the condition key `token.actions.githubusercontent.com:sub` is present and that its value is not solely a wildcard character (\$1 and ?) or null. IAM performs this check when the trust policy is created or updated. If the condition key `token.actions.githubusercontent.com:sub` is not present, or the key value doesn't satisfy the mentioned value criteria, the request will fail and return an error.

**Important**  
If you do not limit the condition key `token.actions.githubusercontent.com:sub` to a specific organization or repository, then GitHub Actions from organizations or repositories outside of your control are able to assume roles associated with the GitHub IAM IdP in your AWS account.

The following example trust policy limits access to the defined GitHub organization, repository, and branch. The condition key `token.actions.githubusercontent.com:sub` value in the following example is the default subject value format documented by GitHub.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::012345678910:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/GitHubRepo:ref:refs/heads/GitHubBranch"
        }
      }
    }
  ]
}
```

------

The following example condition limits access to the defined GitHub organization and repository, but grants access to any branch within the repository.

```
"Condition": {
  "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
  },
  "StringLike": {    
    "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/GitHubRepo:*"
  }
}
```

The following example condition limits access to any repository or branch within the defined GitHub organization. We recommend that you limit the condition key `token.actions.githubusercontent.com:sub` to a specific value that limits access to GitHub Actions from within your GitHub organization.

```
"Condition": {
  "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
  },
  "StringLike": {    
    "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/*"
  }
}
```

For more information about the OIDC federation keys available for condition checks in policies, see [Available keys for AWS OIDC federation](reference_policies_iam-condition-keys.md#condition-keys-wif).

# Create a role for SAML 2.0 federation (console)
Create a role for SAML 2.0 federation

 You can use SAML 2.0 federation instead of creating IAM users in your AWS account. With an identity provider (IdP), you can manage your user identities outside of AWS and give these external user identities permissions to access AWS resources in your account. For more information about federation and identity providers, see [Identity providers and federation into AWS](id_roles_providers.md).

**Note**  
To improve federation resiliency, we recommend that you configure your IdP and AWS federation to support multiple SAML sign-in endpoints. For details, see the AWS Security Blog article [How to use regional SAML endpoints for failover](https://aws.amazon.com/blogs//security/how-to-use-regional-saml-endpoints-for-failover).

## Prerequisites for creating a role for SAML


Before you can create a role for SAML 2.0 federation, you must first complete the following prerequisite steps.<a name="saml-prereqs"></a>

**To prepare to create a role for SAML 2.0 federation**

1. <a name="idpsamlstep1"></a>Before you create a role for SAML-based federation, you must create a SAML provider in IAM. For more information, see [Create a SAML identity provider in IAM](id_roles_providers_create_saml.md).

1. Prepare the policies for the role that the SAML 2.0–authenticated users will assume. As with any role, a role for the SAML federation includes two policies. One is the role trust policy that specifies who can assume the role. The other is the IAM permissions policy that specifies the AWS actions and resources that the SAML federated principal is allowed or denied access to.

   When you create the trust policy for your role, you must use three values to ensure that only your application can assume the role:
   + For the `Action` element, use the `sts:AssumeRoleWithSAML` action.
   + For the `Principal` element, use the string `{"Federated":ARNofIdentityProvider}`. Replace `ARNofIdentityProvider` with the ARN of the [SAML identity provider](id_roles_providers_saml.md) that you created in [Step 1](#idpsamlstep1).
   + For the `Condition` element, use a `StringEquals` condition to test that the `saml:aud` attribute from the SAML response matches the URL your browser displays when signing into the console. This sign-in endpoint URL is your identity provider's SAML recipient attribute. You can include sign-in URLs within particular regions. AWS recommends using Regional endpoints instead of the global endpoint to improve federation resiliency. For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html).

     If SAML encryption is required, the sign-in URL must include the unique identifier AWS assigns to your SAML provider. You can view the unique identifier by selecting the identity provider in the IAM console to display the details page.

     `https://region-code.signin.aws.amazon.com/saml/acs/IdP-ID`

   The following example trust policy is designed for a SAML federated user:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRoleWithSAML",
           "Principal": {
               "Federated": "arn:aws:iam::111122223333:saml-provider/PROVIDER-NAME"
           },
           "Condition": {
               "StringEquals": {
                   "SAML:aud": "https://region-code.signin.aws.amazon.com/saml"
               }
           }
       }
   }
   ```

------

   Replace the principal ARN with the actual ARN for the SAML provider that you created in IAM. It will have your own account ID and provider name. 

## Creating a role for SAML


After you complete the prerequisite steps, you can create the role for SAML-based federation. 

**To create a role for SAML-based federation**

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, choose **Roles** and then choose **Create role**.

1. Choose the **SAML 2.0 federation** role type.

1. For **Select a SAML provider**, choose the provider for your role. 

1. Choose the SAML 2.0 access level method. 
   + Choose **Allow programmatic access only** to create a role that can be assumed programmatically from the AWS API or AWS CLI.
   + Choose **Allow programmatic and AWS Management Console access** to create a role that can be assumed programmatically and from the AWS Management Console.

   The roles created by both are similar, but the role that can also be assumed from the console includes a trust policy with a particular condition. That condition explicitly ensures that the SAML audience (`SAML:aud` attribute) is set to the AWS sign-in endpoint for your SAML provider.

1. The procedure for defining attributes varies depending on the access type.
   + If you're creating a role for programmatic access, choose an attribute from the **Attribute** list. Then, in the **Value** box, enter a value to include in the role. This restricts role access to users from the identity provider whose SAML authentication response (assertion) includes the attributes that you specify. You must specify at least one attribute to ensure that your role is limited to a subset of users at your organization. 
   + If you're creating a role for programmatic and AWS Management Console access, the **Sign-in endpoints** section defines the URL your browser displays when signing into the console. This endpoint is your identity provider's SAML recipient attribute, which maps to the [`saml:aud`](reference_policies_iam-condition-keys.md#condition-keys-saml) context key. For more information, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md).

     1. Choose **Regional endpoints** or **Non-regional endpoint**. We recommend using multiple Regional SAML sign-in endpoints to improve federation resiliency.

     1. For **Regions**, choose the regions that your SAML provider supports for AWS sign-in.

     1.  For **Sign-in URLs to include unique identifiers**, select whether the sign-in endpoints include the unique identifiers AWS assigns to your SAML identity provider. This option is required for encryped SAML assertions. For more information, see [SAML 2.0 federation](id_roles_providers_saml.md).

1. To add more attribute-related conditions to the trust policy, choose **Condition (optional)**, select the additional condition, and specify a value. 
**Note**  
The list includes the most commonly used SAML attributes. IAM supports additional attributes that you can use to create conditions. For a list of the supported attributes, see [Available Keys for SAML Federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-saml). If you need a condition for a supported SAML attribute that's not in the list, you can manually add that condition. To do that, edit the trust policy after you create the role.

1.  Review your SAML 2.0 trust information and then choose **Next**. 

1. IAM includes a list of the AWS managed and customer managed policies in your account. Select the policy to use for the permissions policy, or choose **Create policy** to open a new browser tab and create a new policy from scratch. For more information, see [Creating IAM policies](access_policies_create-console.md#access_policies_create-start). After you create the policy, close that tab and return to your original tab. Select the checkbox next to the permissions policies that you want SAML federated users to have. If you prefer, you can select no policies at this time, and then attach policies to the role later. By default, a role has no permissions.

1. (Optional) Set a [permissions boundary](access_policies_boundaries.md). This is an advanced feature.

   Open the **Permissions boundary** section and choose **Use a permissions boundary to control the maximum role permissions**. Select the policy to use for the permissions boundary.

1. Choose **Next**.

1. Choose **Next: Review**.

1. For **Role name**, enter a role name. Role names must be unique within your AWS account. They are not distinguished by case. For example, you cannot create roles named both **PRODROLE** and **prodrole**. Because other AWS resources might reference the role, you cannot edit the name of the role after it has been created. 

1. (Optional) For **Description**, enter a description for the new role.

1. Choose **Edit** in the **Step 1: Select trusted entities** or **Step 2: Add permissions** sections to edit the use cases and permissions for the role. 

1. (Optional) Add metadata to the role by attaching tags as key–value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.

After you create the role, you complete the SAML trust by configuring your identity provider software with information about AWS. This information includes the roles that you want your SAML federated users to use. This is referred to as configuring the relying party trust between your IdP and AWS. For more information, see [Configure your SAML 2.0 IdP with relying party trust and adding claims](id_roles_providers_create_saml_relying-party.md). 

# Create a role using custom trust policies
Create a role using custom trust policies

You can create a custom trust policy to delegate access and allow others to perform actions in your AWS account. For more information, see [Creating IAM policies](access_policies_create-console.md#access_policies_create-start).

For information about how to use roles to delegate permissions, see [Roles terms and concepts](id_roles.md#id_roles_terms-and-concepts).

## Creating an IAM role using a custom trust policy (console)


You can use the AWS Management Console to create a role that an IAM user can assume. For example, assume that your organization has multiple AWS accounts to isolate a development environment from a production environment. For high-level information about creating a role that allows users in the development account to access resources in the production account, see [Example scenario using separate development and production accounts](id_roles_common-scenarios_aws-accounts.md#id_roles_common-scenarios_aws-accounts-example).

**To create a role using a custom trust policy (console)**

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 console, choose **Roles** and then choose **Create role**.

1. Choose the **Custom trust policy** role type.

1. In the **Custom trust policy** section, enter or paste the custom trust policy for the role. For more information, see [Creating IAM policies](access_policies_create-console.md#access_policies_create-start).

1. Resolve any security warnings, errors, or general warnings generated during [policy validation](access_policies_policy-validator.md), and then choose **Next**.

1. (Optional) Set a [permissions boundary](access_policies_boundaries.md). This is an advanced feature that is available for service roles, but not service-linked roles.

   Open the **Permissions boundary** section and choose **Use a permissions boundary to control the maximum role permissions**. IAM includes a list of the AWS managed and customer managed policies in your account. Select the policy to use for the permissions boundary.

1. Choose **Next**.

1. For **Role name**, the degree of role name customization is defined by the service. If the service defines the role's name, this option is not editable. In other cases, the service might define a prefix for the role and allow you to enter an optional suffix. Some services allow you to specify the entire name of your role.

   If possible, enter a role name or role name suffix. Role names must be unique within your AWS account. They are not distinguished by case. For example, you cannot create roles named both **PRODROLE** and **prodrole**. Because other AWS resources might reference the role, you cannot edit the name of the role after it has been created.

1. (Optional) For **Description**, enter a description for the new role.

1. (Optional) Choose **Edit** in the **Step 1: Select trusted entities** or **Step 2: Add permissions** sections to edit the custom policy and permissions for the role. 

1. (Optional) Add metadata to the role by attaching tags as key–value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.

# Examples of policies for delegating access


The following examples show how you can allow or grant an AWS account access to the resources in another AWS account. To learn how to create an IAM policy using these example JSON policy documents, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

**Topics**
+ [

## Using roles to delegate access to the resources of another AWS account resources
](#example-delegate-xaccount-rolesapi)
+ [

## Using a policy to delegate access to services
](#id_roles_create_policy-examples-access-to-services)
+ [

## Using a resource-based policy to delegate access to an Amazon S3 bucket in another account
](#example-delegate-xaccount-S3)
+ [

## Using a resource-based policy to delegate access to an Amazon SQS queue in another account
](#example-delegate-xaccount-SQS)
+ [

## Cannot delegate access when the account is denied access
](#example-delegate-xaccount-SQS-denied)

## Using roles to delegate access to the resources of another AWS account resources


 For a tutorial that shows how to use IAM roles to grant users in one account access to AWS resources that are in another account, see [IAM tutorial: Delegate access across AWS accounts using IAM roles](tutorial_cross-account-with-roles.md). 

**Important**  
You can include the ARN for a specific role or user in the `Principal` element of a role trust policy. When you save the policy, AWS transforms the ARN to a unique principal ID. This helps mitigate the risk of someone escalating their privileges by removing and recreating the role or user. You don't normally see this ID in the console, because there is also a reverse transformation back to the ARN when the trust policy is displayed. However, if you delete the role or user, then the relationship is broken. The policy no longer applies, even if you recreate the user or role because it does not match the principal ID stored in the trust policy. When this happens, the principal ID shows up in the console because AWS can no longer map it back to an ARN. The result is that if you delete and recreate a user or role referenced in a trust policy's `Principal` element, you must edit the role to replace the ARN. It is transformed into the new principal ID when you save the policy.

## Using a policy to delegate access to services


The following example shows a policy that can be attached to a role. The policy enables two services, Amazon EMR and AWS Data Pipeline, to assume the role. The services can then perform any tasks granted by the permissions policy assigned to the role (not shown). To specify multiple service principals, you do not specify two `Service` elements; you can have only one. Instead, you use an array of multiple service principals as the value of a single `Service` element.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "elasticmapreduce.amazonaws.com",
          "datapipeline.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

## Using a resource-based policy to delegate access to an Amazon S3 bucket in another account


In this example, account A uses a resource-based policy (an Amazon S3 [bucket policy](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucketPolicies.html)) to grant account B full access to account A's S3 bucket. Then account B creates an IAM user policy to delegate that access to account A's bucket to one of the users in account B. 

The S3 bucket policy in account A might look like the following policy. In this example, account A's S3 bucket is named *amzn-s3-demo-bucket*, and account B's account number is 111122223333. It does not specify any individual users or groups in account B, only the account itself.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Sid": "AccountBAccess1",
    "Effect": "Allow",
    "Principal": {"AWS": "111122223333"},
    "Action": "s3:*",
    "Resource": [
      "arn:aws:s3:::amzn-s3-demo-bucket",
      "arn:aws:s3:::amzn-s3-demo-bucket/*"
    ]
  }
}
```

------

Alternatively, account A can use Amazon S3 [Access Control Lists (ACLs)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/S3_ACLs_UsingACLs.html) to grant account B access to an S3 bucket or a single object within a bucket. In that case, the only thing that changes is how account A grants access to account B. Account B still uses a policy to delegate access to an IAM group in account B, as described in the next part of this example. For more information about controlling access on S3 buckets and objects, go to [Access Control](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingAuthAccess.html) in the *Amazon Simple Storage Service User Guide*. 

The administrator of account B might create the following policy sample. The policy allows read access to a group or user in account B. The preceding policy grants access to account B. However, individual groups and users in account B cannot access the resource until a group or user policy explicitly grants permissions to the resource. The permissions in this policy can only be a subset of those in the preceding cross-account policy. Account B cannot grant more permissions to its groups and users than account A granted to account B in the first policy. In this policy, the `Action` element is explicitly defined to allow only `List` actions, and the `Resource` element of this policy matches the `Resource` for the bucket policy implemented by account A.

To implement this policy account B uses IAM to attach it to the appropriate user (or group) in account B. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:List*",
    "Resource": [
      "arn:aws:s3:::amzn-s3-demo-bucket",
      "arn:aws:s3:::amzn-s3-demo-bucket/*"
    ]
  }
}
```

------

## Using a resource-based policy to delegate access to an Amazon SQS queue in another account


In the following example, account A has an Amazon SQS queue that uses a resource-based policy attached to the queue to grant queue access to account B. Then account B uses an IAM group policy to delegate access to a group in account B. 

The following example queue policy gives account B permission to perform the `SendMessage` and `ReceiveMessage` actions on account A's queue named *queue1*, but only between noon and 3:00 p.m. on November 30, 2014. Account B's account number is 1111-2222-3333. Account A uses Amazon SQS to implement this policy. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {"AWS": "111122223333"},
    "Action": [
      "sqs:SendMessage",
      "sqs:ReceiveMessage"
    ],
    "Resource": ["arn:aws:sqs:*:123456789012:queue1"],
    "Condition": {
      "DateGreaterThan": {"aws:CurrentTime": "2014-11-30T12:00Z"},
      "DateLessThan": {"aws:CurrentTime": "2014-11-30T15:00Z"}
    }
  }
}
```

------

Account B's policy for delegating access to a group in account B might look like the following example. Account B uses IAM to attach this policy to a group (or user). 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "sqs:*",
    "Resource": "arn:aws:sqs:*:123456789012:queue1"
  }
}
```

------

In the preceding IAM user policy example, account B uses a wildcard to grant its user access to all Amazon SQS actions on account A's queue. However account B can delegate access only to the extent that account B has been granted access. The account B group that has the second policy can access the queue only between noon and 3:00 p.m. on November 30, 2014. The user can only perform the `SendMessage` and `ReceiveMessage` actions, as defined in account A's Amazon SQS queue policy. 

## Cannot delegate access when the account is denied access


An AWS account cannot delegate access to another account's resources if the other account has explicitly denied access to the user's parent account. The deny propagates to the users under that account whether or not the users have existing policies granting them access.

For example, account A writes a bucket policy on account A's S3 bucket that explicitly denies account B access to account A's bucket. But account B writes an IAM user policy that grants a user in account B access to account A's bucket. The explicit deny applied to account A's S3 bucket propagates to the users in account B. It overrides the IAM user policy granting access to the user in account B. (For detailed information how permissions are evaluated, see [Policy evaluation logic](reference_policies_evaluation-logic.md).) 

Account A's bucket policy might look like the following policy. In this example, account A's S3 bucket is named *amzn-s3-demo-bucket*, and account B's account number is 1111-2222-3333. Account A uses Amazon S3 to implement this policy. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Sid": "AccountBDeny",
    "Effect": "Deny",
    "Principal": {"AWS": "111122223333"},
    "Action": "s3:*",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
  }
}
```

------

This explicit deny overrides any policies in account B that provide permission to access the S3 bucket in account A. 

# IAM role management
Role management

Before a user, application, or service can use a role that you created, you must grant permissions to switch to the role. You can use any policy attached to groups or users to grant the necessary permissions. This section describes how to grant users permission to use a role. It also explains how the user can switch to a role from the AWS Management Console, the Tools for Windows PowerShell, the AWS Command Line Interface (AWS CLI) and the [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API.

**Important**  
When you create a role programmatically instead of in the IAM console, you have an option to add a `Path` of up to 512 characters in addition to the `RoleName`, which can be up to 64 characters long. However, if you intend to use a role with the **Switch Role** feature in the AWS Management Console, then the combined `Path` and `RoleName` cannot exceed 64 characters.

**Topics**
+ [

## View role access
](#roles-modify_prerequisites)
+ [

## Generate a policy based on access information
](#roles-modify_gen-policy)
+ [

# Grant a user permissions to switch roles
](id_roles_use_permissions-to-switch.md)
+ [

# Grant a user permissions to pass a role to an AWS service
](id_roles_use_passrole.md)
+ [

# Revoke IAM role temporary security credentials
](id_roles_use_revoke-sessions.md)
+ [

# Update a service-linked role
](id_roles_update-service-linked-role.md)
+ [

# Update a role trust policy
](id_roles_update-role-trust-policy.md)
+ [

# Update permissions for a role
](id_roles_update-role-permissions.md)
+ [

# Update settings for a role
](id_roles_update-role-settings.md)
+ [

# Delete roles or instance profiles
](id_roles_manage_delete.md)

## View role access


Before you change the permissions for a role, you should review its recent service-level activity. This is important because you don't want to remove access from a principal (person or application) who is using it. For more information about viewing last accessed information, see [Refine permissions in AWS using last accessed information](access_policies_last-accessed.md).

## Generate a policy based on access information


You might sometimes grant permissions to an IAM entity (user or role) beyond what they require. To help you refine the permissions that you grant, you can generate an IAM policy that is based on the access activity for an entity. IAM Access Analyzer reviews your AWS CloudTrail logs and generates a policy template that contains the permissions that have been used by the entity in your specified date range. You can use the template to create a managed policy with fine-grained permissions and then attach it to the IAM entity. That way, you grant only the permissions that the user or role needs to interact with AWS resources for your specific use case. To learn more, see [IAM Access Analyzer policy generation](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html).

# Grant a user permissions to switch roles
Grant permissions to switch roles

When an administrator [creates a role for cross-account access](id_roles_create_for-user.md), they establish trust between the account that owns the role, the resources (trusting account), and the account that contains the users (trusted account). To do this, the administrator of the trusting account specifies the trusted account number as the `Principal` in the role's trust policy. That *potentially* allows any user in the trusted account to assume the role. To complete the configuration, the administrator of the trusted account must give specific groups or users in that account permission to switch to the role.

**To grant permission to switch to a role**

1. As the administrator of the trusted account, create a new policy for the user, or edit an existing policy to add the required elements. For details, see [Creating or editing the policy](#roles-usingrole-createpolicy).

1. Then, choose how you want to share the role information: 
   + **Role link:** Send users a link that takes them to the **Switch Role** page with all the details already filled in. 
   + **Account ID or alias:** Provide each user with the role name along with the account ID number or account alias. The user then goes to the **Switch Role** page and adds the details manually. 

   For details, see [Providing information to the user](#roles-usingrole-giveuser).

Note that you can switch roles only when you sign in as an IAM user, a SAML-federated role, or a web-identity federated role. You cannot switch roles when you sign in as the AWS account root user.

**Important**  
You cannot switch roles in the AWS Management Console to a role that requires an [ExternalId](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) value. You can switch to such a role only by calling the [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API that supports the `ExternalId` parameter.

**Notes**  
This topic discusses policies for a *user*, because you are ultimately granting permissions to a user to accomplish a task. However, we don't recommend that you grant permissions directly to an individual user. When a user assumes a role, they are assigned the permissions associated with that role.
When you switch roles in the AWS Management Console, the console always uses your original credentials to authorize the switch. This applies whether you sign in as an IAM user, as a SAML-federated role, or as a web-identity federated role. For example, if you switch to RoleA, IAM uses your original user or federated role credentials to determine if you are allowed to assume RoleA. If you then try to switch to RoleB *while you are using RoleA*, your **original** user or federated role credentials are used to authorize your attempt. The credentials for RoleA are not used for this action.

**Topics**
+ [

## Creating or editing the policy
](#roles-usingrole-createpolicy)
+ [

## Providing information to the user
](#roles-usingrole-giveuser)

## Creating or editing the policy


A policy that grants a user permission to assume a role must include a statement with the `Allow` effect on the following: 
+ The `sts:AssumeRole` action
+ The Amazon Resource Name (ARN) of the role in a `Resource` element

Users that get the policy are allowed to switch roles on the resource listed (either through group membership or directly attached).

**Note**  
If `Resource` is set to `*`, the user can assume any role in any account that trusts the user's account. (In other words, the role's trust policy specifies the user's account as `Principal`). As a best practice, we recommend that you follow the [principle of least privilege](http://en.wikipedia.org/wiki/Principle_of_least_privilege) and specify the complete ARN for only the roles that the user needs.

The following example shows a policy that lets the user assume roles in only one account. In addition, the policy uses a wildcard (\$1) to specify that the user can switch to a role only if the role name begins with the letters `Test`.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::111122223333:role/Test*"
    }
}
```

------

**Note**  
The permissions that the role grants to the user do not add to the permissions already granted to the user. When a user switches to a role, the user temporarily gives up his or her original permissions in exchange for those granted by the role. When the user exits the role, then the original user permissions are automatically restored. For example, let's say the user's permissions allow working with Amazon EC2 instances, but the role's permissions policy does not grant those permissions. In that case, while using the role, the user cannot work with Amazon EC2 instances in the console. In addition, temporary credentials obtained via `AssumeRole` do not work with Amazon EC2 instances programmatically.

## Providing information to the user


After you create a role and grant your user permissions to switch to it, you must provide the user with the following:
+ The name of the role
+ The ID or alias of the account that contains the role

You can streamline access for your users by sending them a link that is preconfigured with the account ID and role name. You can see the role link after completing the **Create Role** wizard by selecting the **View Role** banner, or on the **Role Summary** page for any cross-account enabled role.

You can also use the following format to manually construct the link. Substitute your account ID or alias and the role name for the two parameters in the following example.

`https://signin.aws.amazon.com/switchrole?account=your_account_ID_or_alias&roleName=optional_path/role_name`

We recommend that you direct your users to [Switch from a user to an IAM role (console)](id_roles_use_switch-role-console.md) to walk them through the process. To troubleshoot common issues that you might encounter when you assume a role, see [I can't assume a role](troubleshoot_roles.md#troubleshoot_roles_cant-assume-role).

**Considerations**
+ If you create the role programmatically, you can create the role with a path and a name. If you do so, you must provide the complete path and role name to your users so they can enter it on the **Switch Role** page of the AWS Management Console. For example: `division_abc/subdivision_efg/role_XYZ`.
+ If you create the role programmatically, you can add a `Path` of up to 512 characters and a `RoleName`. The role name can be up to 64 characters long. However, to use a role with the **Switch Role** feature in the AWS Management Console, the combined `Path` and `RoleName` cannot exceed 64 characters.
+ For security purposes, you can [review AWS CloudTrail logs](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds) to learn who performed an action in AWS. You can use the `sts:SourceIdentity` condition key in the role trust policy to require users to specify an identity when they assume a role. For example, you can require that IAM users specify their own user name as their source identity. This can help you determine which user performed a specific action in AWS. For more information, see [`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity). You can also use [`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname) to require users to specify a session name when they assume a role. This can help you differentiate between role sessions when a role is used by different principals.

# Grant a user permissions to pass a role to an AWS service
Grant permissions to pass a role to a service

To configure many AWS services, you must *pass* an IAM role to the service. This allows the service to assume the role later and perform actions on your behalf. For most services, you only have to pass the role to the service once during setup, and not every time that the service assumes the role. For example, assume that you have an application running on an Amazon EC2 instance. That application requires temporary credentials for authentication, and permissions to authorize the application to perform actions in AWS. When you set up the application, you must pass a role to Amazon EC2 to use with the instance that provides those credentials. You define the permissions for the applications running on the instance by attaching an IAM policy to the role. The application assumes the role every time it needs to perform the actions that are allowed by the role.

To pass a role (and its permissions) to an AWS service, a user must have permissions to *pass the role* to the service. This helps administrators ensure that only approved users can configure a service with a role that grants permissions. To allow a user to pass a role to an AWS service, you must grant the `PassRole` permission to the user's IAM user, role, or group.

**Warning**  
You can only use the `PassRole` permission to pass an IAM role to a service that shares the same AWS account. To pass a role in Account A to a service in Account B, you must first create an IAM role in Account B that can assume the role from Account A, and then the role in Account B can be passed to the service. For details, see [Cross account resource access in IAM](access_policies-cross-account-resource-access.md).
Do not try to control who can pass a role by tagging the role and then using the `ResourceTag` condition key in a policy with the `iam:PassRole` action. This approach does not have reliable results.

When setting the `PassRole` permission, you should make sure that a user doesn’t pass a role where the role has more permissions than you want the user to have. For example, Alice might not be allowed to perform any Amazon S3 actions. If Alice could pass a role to a service that allows Amazon S3 actions, the service could perform Amazon S3 actions on behalf of Alice when executing the job.

When you specify a service-linked role, you must also have permission to pass that role to the service. Some services automatically create a service-linked role in your account when you perform an action in that service. For example, Amazon EC2 Auto Scaling creates the `AWSServiceRoleForAutoScaling` service-linked role for you when you create an Auto Scaling group for the first time. If you try to specify the service-linked role when you create an Auto Scaling group and you don't have the `iam:PassRole` permission, you receive an error. If you don't explicitly specify the role, the `iam:PassRole` permission is not required, and the default is to use `AWSServiceRoleForAutoScaling` role for all operations that are performed on that group. To learn which services support service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md). To learn which services automatically create a service-linked role when you perform an action in that service, choose the **Yes** link and view the service-linked role documentation for the service.

A user can pass a role ARN as a parameter in any API operation that uses the role to assign permissions to the service. The service then checks whether that user has the `iam:PassRole` permission. To limit the user to passing only approved roles, you can filter the `iam:PassRole` permission with the `Resources` element of the IAM policy statement. 

You can use the `Condition` element in a JSON policy to test the value of keys included in the request context of all AWS requests. To learn more about using condition keys in a policy, see [IAM JSON policy elements: Condition](reference_policies_elements_condition.md). The `iam:PassedToService` condition key can be used to specify the service principal of the service to which a role can be passed. To learn more about using the `iam:PassedToService` condition key in a policy, see [iam:PassedToService](reference_policies_iam-condition-keys.md#ck_PassedToService).

**Example 1**  
Suppose you want to grant a user the ability to pass any of an approved set of roles to the Amazon EC2 service upon launching an instance. You need three elements:
+ An IAM *permissions policy* attached to the role that determines what the role can do. Scope permissions to only the actions that the role must perform, and to only the resources that the role needs for those actions. You can use an AWS managed or customer-created IAM permissions policy.

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": {
          "Effect": "Allow",
          "Action": [ "A list of the permissions the role is allowed to use" ],
          "Resource": [ "A list of the resources the role is allowed to access" ]
      }
  }
  ```

------
+ A* trust policy* for the role that allows the service to assume the role. For example, you could attach the following trust policy to the role with the `UpdateAssumeRolePolicy` action. This trust policy allows Amazon EC2 to use the role and the permissions attached to the role.

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": {
          "Sid": "TrustPolicyStatementThatAllowsEC2ServiceToAssumeTheAttachedRole",
          "Effect": "Allow",
          "Principal": { "Service": "ec2.amazonaws.com" },
         "Action": "sts:AssumeRole"
      }
  }
  ```

------
+ An IAM *permissions policy* attached to the IAM user that allows the user to pass only those approved roles. You usually add `iam:GetRole` to `iam:PassRole` so the user can get the details of the role to be passed. In this example, the user can pass only roles that exist in the specified account with names beginning with `EC2-roles-for-XYZ-`:

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "iam:GetRole",
                  "iam:PassRole"
              ],
              "Resource": "arn:aws:iam::111122223333:role/EC2-roles-for-XYZ-*"
          }
      ]
  }
  ```

------

Now the user can start an Amazon EC2 instance with an assigned role. Applications running on the instance can access temporary credentials for the role through the instance profile metadata. The permissions policies attached to the role determine what the instance can do. 

**Example 2**  
Amazon Relational Database Service (Amazon RDS) supports a feature called **Enhanced Monitoring**. This feature enables Amazon RDS to monitor a database instance using an agent. It also allows Amazon RDS to log metrics to Amazon CloudWatch Logs. To enable this feature, you must create a service role to give Amazon RDS permissions to monitor and write metrics to your logs. 

**To create a role for Amazon RDS enhanced monitoring**

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. Choose **Roles**, and then choose **Create role**.

1. Choose the **AWS Service** role type, and then for **Use cases for other AWS services**, choose the **RDS** service. Choose **RDS – Enhanced Monitoring**, and then choose **Next**.

1. Choose the **AmazonRDSEnhancedMonitoringRole** permissions policy.

1. Choose **Next**.

1. For **Role name**, enter a role name that helps you identify the purpose of this role. Role names must be unique within your AWS account. When a role name is used in a policy or as part of an ARN, the role name is case sensitive. When a role name appears to customers in the console, such as during the sign-in process, the role name is case insensitive. Because various entities might reference the role, you can't edit the name of the role after it is created.

1. (Optional) For **Description**, enter a description for the new role.

1. (Optional) Add metadata to the user by attaching tags as key-value pairs. For more information about using tags in IAM, see [Tags for AWS Identity and Access Management resources](id_tags.md).

1. Review the role and then choose **Create role**.

The role automatically gets a trust policy that grants the `monitoring.rds.amazonaws.com` service permissions to assume the role. After it does, Amazon RDS can perform all of the actions that the `AmazonRDSEnhancedMonitoringRole` policy allows.

The user that you want to access Enhanced Monitoring needs a policy that includes a statement that allows the user to to list the RDS roles and a statement that allows the user to pass the role, like the following. Use your account number and replace the role name with the name you provided in step 6.

```
    {
      "Sid": "PolicyStatementToAllowUserToListRoles",
      "Effect": "Allow",
      "Action": ["iam:ListRoles"],
      "Resource": "*"
    },
    {
        "Sid": "PolicyStatementToAllowUserToPassOneSpecificRole",
        "Effect": "Allow",
        "Action": [ "iam:PassRole" ],
        "Resource": "arn:aws:iam::account-id:role/RDS-Monitoring-Role"
    }
```

You can combine this statement with statements in another policy or put it in its own policy. To instead specify that the user can pass any role that begins with `RDS-`, you can replace the role name in the resource ARN with a wildcard, as follows.

```
        "Resource": "arn:aws:iam::account-id:role/RDS-*"
```

## `iam:PassRole` actions in AWS CloudTrail logs


 `PassRole` is not an API call. `PassRole` is a permission, meaning no CloudTrail logs are generated for IAM `PassRole`. To review what roles are passed to which AWS services in CloudTrail, you must review the CloudTrail log that created or modified the AWS resource receiving the role. For example, a role is passed to an AWS Lambda function when it's created. The log for the `CreateFunction` action shows a record of role that was passed to the function. 

# Revoke IAM role temporary security credentials
Revoke role temporary credentials

**Warning**  
If you follow the steps on this page, all users with current sessions created by assuming the role are denied access to all AWS actions and resources. This can result in users losing unsaved work.

When you permit users to access the AWS Management Console with a long session duration time (such as 12 hours), their temporary credentials do not expire as quickly. If users inadvertently expose their credentials to an unauthorized third-party, that party has access for the duration of the session. However, you can immediately revoke all permissions to the role's credentials issued before a certain point in time if you need to. All temporary credentials for that role issued before the specified time become invalid. This forces all users to re-authenticate and request new credentials.

 

**Note**  
You cannot revoke the session for a *[service-linked role](id_roles.md#iam-term-service-linked-role)*.

When you revoke permissions for a role using the procedure in this topic, AWS attaches a new inline policy to the role that denies all permissions to all actions. It includes a condition that applies the restrictions only if the user assumed the role *before* the point in time when you revoke the permissions. If the user assumes the role *after* you revoked the permissions, then the deny policy does not apply to that user.

For more information on denying access, see [Disabling permissions for temporary security credentials](id_credentials_temp_control-access_disable-perms.md).

**Important**  
This deny policy applies to all users of the specified role, not just those with longer duration console sessions.

## Minimum permissions to revoke session permissions from a role


To successfully revoke session permissions from a role, you must have the `PutRolePolicy` permission for the role. This allows you to attach the `AWSRevokeOlderSessions` inline policy to the role.

## Revoking session permissions


You can revoke the session permissions from a role to deny all permissions to any user who assumed the role.

**Note**  
You can't edit roles in IAM that were created from IAM Identity Center permission sets. You must revoke the active permission set session for a user in IAM Identity Center. For more information, see [Revoke active IAM role sessions created by permission sets](https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#revoke-user-permissions) in the *IAM Identity Center User Guide*.

**To immediately deny all permissions to any current user of role credentials**

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, choose **Roles**, and then choose the name (not the checkbox) of the role whose permissions you want to revoke.

1. On the **Summary** page for the selected role, choose the **Revoke sessions** tab.

1. On the **Revoke sessions** tab, choose **Revoke active sessions**.

1. AWS asks you to confirm the action. Select the **I acknowledge that I am revoking all active sessions for this role.** checkbox and choose **Revoke active sessions** on the dialog box.

   IAM then attaches a policy named `AWSRevokeOlderSessions` to the role. After you choose **Revoke active sessions**, the policy denies all access to users who assumed the role in the past as well as approximately 30 seconds into the future. This future time choice takes into account the propagation delay of the policy in order to deal with a new session that was acquired or renewed before the updated policy is in effect in a given region. Any user who assumes the role more than approximately 30 seconds after you choose Revoke active sessions is not affected. To learn why changes are not always immediately visible, see [Changes that I make are not always immediately visible](troubleshoot.md#troubleshoot_general_eventual-consistency). 

**Note**  
If you choose to **Revoke active sessions** again later, the date and time stamp in the policy is refreshed and it again denies all permissions to any user who assumed the role before the new specified time.

Valid users whose sessions are revoked in this way must acquire temporary credentials for a new session to continue working. The AWS CLI caches credentials until they expire. To force the CLI to delete and refresh cached credentials that are no longer valid, run one of the following commands:

**Linux, macOS, or Unix**

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

**Windows**

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

## Revoking session permissions before a specified time


 You can also revoke session permissions at any time of your choice using the AWS CLI or SDK to specify a value for the `aws:TokenIssueTime` key in the Condition element of a policy. 

This policy denies all permissions when the value of `aws:TokenIssueTime` is earlier than the specified date and time. The value of `aws:TokenIssueTime` corresponds to the exact time at which the temporary security credentials were created. The `aws:TokenIssueTime` value is only present in the context of AWS requests that are signed with temporary security credentials, so the Deny statement in the policy does not affect requests that are signed with the long-term credentials of the IAM user.

This policy can also be attached to a role. In that case, the policy affects only the temporary security credentials that were created by the role before the specified date and time.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "DateLessThan": {"aws:TokenIssueTime": "2014-05-07T23:47:00Z"}
    }
  }
}
```

------

Valid users whose sessions are revoked in this way must acquire temporary credentials for a new session to continue working. The AWS CLI caches credentials until they expire. To force the CLI to delete and refresh cached credentials that are no longer valid, run one of the following commands:

**Linux, macOS, or Unix**

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

**Windows**

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

# Update a service-linked role


The method that you use to edit a service-linked role depends on the service. Some services might allow you to edit the permissions for a service-linked role from the service console, API, or CLI. However, after you create a service-linked role, you cannot change the name of the role because various entities might reference the role. You can edit the description of any role from the IAM console, API, or CLI.

For information about which services support using service-linked roles, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-Linked Role** column. To learn whether the service supports editing the service-linked role, choose the **Yes** link to view the service-linked role documentation for that service.

## Editing a service-linked role description (console)


You can use the IAM console to edit the description of a service-linked role.

**To edit the description of a service-linked role (console)**

1. In the navigation pane of the IAM console, choose **Roles**.

1. Choose the name of the role to modify.

1. To the far right of **Role description**, choose **Edit**. 

1. Enter a new description in the box and choose **Save**.

## Editing a service-linked role description (AWS CLI)


You can use IAM commands from the AWS CLI to edit the description of a service-linked role.

**To change the description of a service-linked role (AWS CLI)**

1. (Optional) To view the current description for a role, run the following commands:

   ```
   aws iam [get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html) --role-name ROLE-NAME
   ```

   Use the role name, not the ARN, to refer to roles with the CLI commands. For example, if a role has the following ARN: `arn:aws:iam::123456789012:role/myrole`, you refer to the role as **myrole**.

1. To update a service-linked role's description, run the following command:

   ```
   aws iam [update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html) --role-name ROLE-NAME --description OPTIONAL-DESCRIPTION
   ```

## Editing a service-linked role description (AWS API)


You can use the AWS API to edit the description of a service-linked role.

**To change the description of a service-linked role (AWS API)**

1. (Optional) To view the current description for a role, call the following operation, and specify the name of the role:

   AWS API: [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. To update a role's description, call the following operation, and specify the name (and optional description) of the role: 

   AWS API: [UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html) 

# Update a role trust policy


To change who can assume a role, you must modify the role's trust policy. You cannot modify the trust policy for a *[service-linked role](id_roles.md#iam-term-service-linked-role)*.

**Notes**  
If a user is listed as the principal in a role's trust policy but cannot assume the role, check the user's [permissions boundary](access_policies_boundaries.md). If a permissions boundary is set for the user, then it must allow the `sts:AssumeRole` action.
To allow users to assume the current role again within a role session, specify the role ARN or AWS account ARN as a principal in the role trust policy. AWS services that provide compute resources such as Amazon EC2, Amazon ECS, Amazon EKS, and Lambda provide temporary credentials and automatically update these credentials. This ensures that you always have a valid set of credentials. For these services, it's not necessary to assume the current role again to obtain temporary credentials. However, if you intend to pass [session tags](id_session-tags.md) or a [session policy](access_policies.md#policies_session), you need to assume the current role again.


## Updating a role trust policy (console)


**To change a role trust policy in the AWS Management Console**

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, choose **Roles**.

1. In the list of roles in your account, choose the name of the role that you want to modify.

1. Choose the **Trust relationships** tab, and then choose **Edit trust policy**.

1. Edit the trust policy as needed. To add additional principals that can assume the role, specify them in the `Principal` element. For example, the following policy snippet shows how to reference two AWS accounts in the `Principal` element:

   ```
   "Principal": {
     "AWS": [
       "arn:aws:iam::111122223333:root",
       "arn:aws:iam::444455556666:root"
     ]
   },
   ```

   If you specify a principal in another account, adding an account to the trust policy of a role is only half of establishing the cross-account trust relationship. By default, no users in the trusted accounts can assume the role. The administrator for the newly trusted account must grant the users the permission to assume the role. To do that, the administrator must create or edit a policy that is attached to the user to allow the user access to the `sts:AssumeRole` action. For more information, see the following procedure or [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

   The following policy snippet shows how to reference two AWS services in the `Principal` element:

   ```
   "Principal": {
     "Service": [
       "opsworks.amazonaws.com",
       "ec2.amazonaws.com"
     ]
   },
   ```

1. When you are finished editing your trust policy, choose **Update policy** to save your changes.

   For more information about policy structure and syntax, see [Policies and permissions in AWS Identity and Access Management](access_policies.md) and the [IAM JSON policy element reference](reference_policies_elements.md).

**To allow users in a trusted external account to use the role (console)**

For more information and detail about this procedure, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. Sign in to the trusted external AWS account. 

1. Decide whether to attach the permissions to a user or to a group. In the navigation pane of the IAM console, choose **Users** or **User groups** accordingly.

1. Choose the name of the user or group to which you want to grant access, and then choose the **Permissions** tab.

1. Do one of the following:
   + To edit a customer managed policy, choose the name of the policy, choose **Edit policy**, and then choose the **JSON** tab. You cannot edit an AWS managed policy. AWS managed policies appear with the AWS icon (![\[Orange cube icon indicating a policy is managed by AWS.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/policy_icon.png)). For more information about the difference between AWS managed policies and customer managed policies, see [Managed policies and inline policies](access_policies_managed-vs-inline.md).
   + To edit an inline policy, choose the arrow next to the name of the policy and choose **Edit policy**.

1. In the policy editor, add a new `Statement` element that specifies the following:

   ```
   {
     "Effect": "Allow",
     "Action": "sts:AssumeRole",
     "Resource": "arn:aws:iam::ACCOUNT-ID:role/ROLE-NAME"
   }
   ```

   Replace the ARN in the statement with the ARN of the role that the user can assume.

1. Follow the prompts on screen to finish editing the policy. 

## Updating a role trust policy (AWS CLI)


You can use the AWS CLI to change who can assume a role.

**To modify a role trust policy (AWS CLI)**

1. (Optional) If you don't know the name of the role that you want to modify, run the following command to list the roles in your account:
   + [aws iam list-roles](https://docs.aws.amazon.com/cli/latest/reference/iam/list-roles.html)

1. (Optional) To view the current trust policy for a role, run the following command:
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. To modify the trusted principals that can access the role, create a text file with the updated trust policy. You can use any text editor to construct the policy.

   For example, the following trust policy shows how to reference two AWS accounts in the `Principal` element. This allows users within two separate AWS accounts to assume this role.

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

****  

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

------

   If you specify a principal in another account, adding an account to the trust policy of a role is only half of establishing the cross-account trust relationship. By default, no users in the trusted accounts can assume the role. The administrator for the newly trusted account must grant the users the permission to assume the role. To do that, the administrator must create or edit a policy that is attached to the user to allow the user access to the `sts:AssumeRole` action. For more information, see the following procedure or [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. To use the file that you just created to update the trust policy, run the following command:
   + [aws iam update-assume-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/update-assume-role-policy.html)

**To allow users in a trusted external account to use the role (AWS CLI)**

For more information and detail about this procedure, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. Create a JSON file that contains a permissions policy that grants permissions to assume the role. For example, the following policy contains the minimum necessary permissions:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRole",
           "Resource": "arn:aws:iam::111122223333:role/ROLE-NAME"
       }
   }
   ```

------

   Replace the ARN in the statement with the ARN of the role that the user can assume.

1. Run the following command to upload the JSON file that contains the trust policy to IAM:
   + [aws iam create-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy.html)

   The output of this command includes the ARN of the policy. Make a note of this ARN because you will need it in a later step. 

1. Decide which user or group to attach the policy to. If you don't know the name of the intended user or group, use one of the following commands to list the users or groups in your account:
   + [aws iam list-users](https://docs.aws.amazon.com/cli/latest/reference/iam/list-users.html)
   + [aws iam list-groups](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups.html)

1. Use one of the following commands to attach the policy that you created in the previous step to the user or group:
   + [aws iam attach-user-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html)
   + [aws iam attach-group-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-group-policy.html)

## Updating a role trust policy (AWS API)


You can use the AWS API to change who can assume a role.

**To modify a role trust policy (AWS API)**

1. (Optional) If you don't know the name of the role that you want to modify, call the following operation to list the roles in your account:
   + [ListRoles](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRoles.html)

1. (Optional) To view the current trust policy for a role, call the following operation:
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html)

1. To modify the trusted principals that can access the role, create a text file with the updated trust policy. You can use any text editor to construct the policy.

   For example, the following trust policy shows how to reference two AWS accounts in the `Principal` element. This allows users within two separate AWS accounts to assume this role.

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

****  

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

------

   If you specify a principal in another account, adding an account to the trust policy of a role is only half of establishing the cross-account trust relationship. By default, no users in the trusted accounts can assume the role. The administrator for the newly trusted account must grant the users the permission to assume the role. To do that, the administrator must create or edit a policy that is attached to the user to allow the user access to the `sts:AssumeRole` action. For more information, see the following procedure or [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. To use the file that you just created to update the trust policy, call the following operation:
   + [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAssumeRolePolicy.html)

**To allow users in a trusted external account to use the role (AWS API)**

For more information and detail about this procedure, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).

1. Create a JSON file that contains a permissions policy that grants permissions to assume the role. For example, the following policy contains the minimum necessary permissions:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRole",
           "Resource": "arn:aws:iam::111122223333:role/ROLE-NAME"
       }
   }
   ```

------

   Replace the ARN in the statement with the ARN of the role that the user can assume.

1. Call the following operation to upload the JSON file that contains the trust policy to IAM:
   + [CreatePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicy.html)

   The output of this operation includes the ARN of the policy. Make a note of this ARN because you will need it in a later step. 

1. Decide which user or group to attach the policy to. If you don't know the name of the intended user or group, call one of the following operations to list the users or groups in your account:
   + [ListUsers](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUsers.html)
   + [ListGroups](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html)

1. Call one of the following operations to attach the policy that you created in the previous step to the user or group:
   +  API: [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html)
   + [AttachGroupPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachGroupPolicy.html)

# Update permissions for a role
Update role permissions

Use the following procedures to update a role's permissions policies and permissions boundaries.

## Prerequisite: View role access


Before you change the permissions for a role, you should review its recent service-level activity. This is important because you don't want to remove access from a principal (person or application) who is using it. For more information about viewing last accessed information, see [Refine permissions in AWS using last accessed information](access_policies_last-accessed.md).

## Update the permissions policy for a role
Update permissions policy

To change the permissions allowed by the role, modify the role's permissions policy (or policies). You cannot modify the permissions policy for a *[service-linked role](id_roles.md#iam-term-service-linked-role)* in IAM. You might be able to modify the permissions policy within the service that depends on the role. To check whether a service supports this feature, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-linked roles** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

### Updating a role permissions policy (console)


**To change the permissions allowed by a role (console)**

1. 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, choose **Roles**.

1. Choose the name of the role that you want to modify, and then choose the **Permissions** tab.

1. Do one of the following:
   + To edit an existing customer managed policy, choose the name of the policy and then choose **Edit policy**.
**Note**  
You cannot edit an AWS managed policy. AWS managed policies appear with the AWS icon (![\[Orange cube icon indicating a policy is managed by AWS.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/policy_icon.png)). For more information about the difference between AWS managed policies and customer managed policies, see [Managed policies and inline policies](access_policies_managed-vs-inline.md). 
   + To attach an existing managed policy to the role, choose **Add permissions** and then choose **Attach policies**.
   + To edit an existing inline policy, expand the policy and choose **Edit**.
   + To embed a new inline policy, choose **Add permissions** and then choose **Create inline policy**. 
   + To remove an existing policy from the role, select the check box next to the policy name and then choose **Remove**.

### Updating a role permissions policy (AWS CLI)


To change the permissions allowed by the role, modify the role's permissions policy (or policies). You cannot modify the permissions policy for a *[service-linked role](id_roles.md#iam-term-service-linked-role)* in IAM. You might be able to modify the permissions policy within the service that depends on the role. To check whether a service supports this feature, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-linked roles** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

**To change the permissions allowed by a role (AWS CLI)**

1. (Optional) To view the current permissions associated with a role, run the following commands:

   1. [aws iam list-role-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-role-policies.html) to list inline policies

   1. [aws iam list-attached-role-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-role-policies.html) to list managed policies

1. The command to update permissions for the role differs depending on whether you are updating a managed policy or an inline policy.

   To update a managed policy, run the following command to create a new version of the managed policy:
   + [aws iam create-policy-version](https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy-version.html)

   To update an inline policy, run the following command:
   + [aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

### Updating a role permissions policy (AWS API)


To change the permissions allowed by the role, modify the role's permissions policy (or policies). You cannot modify the permissions policy for a *[service-linked role](id_roles.md#iam-term-service-linked-role)* in IAM. You might be able to modify the permissions policy within the service that depends on the role. To check whether a service supports this feature, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and look for the services that have **Yes **in the **Service-linked roles** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

**To change the permissions allowed by a role (AWS API)**

1. (Optional) To view the current permissions associated with a role, call the following operations:

   1. [ListRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRolePolicies.html) to list inline policies

   1. [ListAttachedRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedRolePolicies.html) to list managed policies

1. The operation to update permissions for the role differs depending on whether you are updating a managed policy or an inline policy.

   To update a managed policy, call the following operation to create a new version of the managed policy:
   + [CreatePolicyVersion](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html)

   To update an inline policy, call the following operation:
   + [PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

## Update the permissions boundary for a role
Update permissions boundary

To change the maximum permissions allowed for a role, modify the role's [permissions boundary](access_policies_boundaries.md).

### Updating a role permissions boundary (console)
Update permissions boundary (console)

**To change the policy used to set the permissions boundary for a role**

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, choose **Roles**.

1. Choose the name of the role with the [permissions boundary](access_policies_boundaries.md) that you want to change. 

1. Choose the **Permissions** tab. If necessary, open the **Permissions boundary** section and then choose **Change boundary**.

1. Select the policy that you want to use for the permissions boundary.

1. Choose **Change boundary**.

   Your changes don't take effect until the next time someone assumes this role.

### Updating a role permissions boundary (AWS CLI)
Update permissions boundary (AWS CLI)

**To change the managed policy used to set the permissions boundary for a role (AWS CLI)**

1. (Optional) To view the current [permissions boundary](access_policies_boundaries.md) for a role, run the following command: 
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. To use a different managed policy to update the permissions boundary for a role, run the following command: 
   + [aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   A role can have only one managed policy set as a permissions boundary. If you change the permissions boundary, you change the maximum permissions allowed for a role.

### Updating a role permissions boundary (AWS API)
Update permissions boundary (API)

**To change the managed policy used to set the permissions boundary for a role (AWS API)**

1. (Optional) To view the current [permissions boundary](access_policies_boundaries.md) for a role, call the following operation: 
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html)

1. To use a different managed policy to update the permissions boundary for a role, call the following operation: 
   + [PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   A role can have only one managed policy set as a permissions boundary. If you change the permissions boundary, you change the maximum permissions allowed for a role.

# Update settings for a role
Update role settings

Use the following procedures to update a role's description or change the maximum session duration for a role.

## Update a role description


To change the description of the role, modify the description text.

### Updating a role description (console)


**To change the description of a role (console)**

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, choose **Roles**.

1. Choose the name of the role to modify.

1. In the **Summary** section, choose **Edit**.

1. Enter a new description in the box and choose **Save changes**.

### Updating a role description (AWS CLI)


**To change the description of a role (AWS CLI)**

1. (Optional) To view the current description for a role, run the following command:
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. To update a role's description, run the following command with the description parameter:
   + [aws iam update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html)

### Updating a role description (AWS API)


**To change the description of a role (AWS API)**

1. (Optional) To view the current description for a role, call the following operation:
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. To update a role's description, call the following operation with the description parameter:
   + [UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html)

## Update the maximum session duration for a role


To specify the maximum session duration setting for roles that are assumed using the console, the AWS CLI, or AWS API, modify the maximum session duration setting value. This setting can have a value from 1 hour to 12 hours. If you do not specify a value, the default maximum of 1 hour is applied. This setting does not limit sessions assumed by AWS services.

### Updating the maximum role session duration (console)
<a name="id_roles_modify_max-session"></a>

**To change the maximum session duration setting for roles that are assumed using the console, AWS CLI, or AWS API (console)**

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, choose **Roles**.

1. Choose the name of the role to modify.

1. In the **Summary** section, choose **Edit**.

1. For **Maximum session duration**, choose a value. Alternatively, choose **Custom duration** and enter a value (in seconds).

1. Choose **Save changes**.

   Your changes don't take effect until the next time someone assumes this role. To learn how to revoke existing sessions for this role, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md).

In the AWS Management Console, IAM user sessions are 12 hours by default. IAM users who switch roles in the console are granted the role maximum session duration, or the remaining time in the user's session, whichever is less.

Anyone who assumes the role from the AWS CLI or AWS API can request a longer session, up to this maximum. The `MaxSessionDuration` setting determines the maximum duration of the role session that can be requested.
+ To specify a session duration using the AWS CLI use the `duration-seconds` parameter. To learn more, see [Switch to an IAM role (AWS CLI)](id_roles_use_switch-role-cli.md).
+ To specify a session duration using the AWS API, use the `DurationSeconds` parameter. To learn more, see [Switch to an IAM role (AWS API)](id_roles_use_switch-role-api.md). 

### Updating the maximum role session duration (AWS CLI)


**Note**  
Anyone who assumes the role from the AWS CLI or API can use the `duration-seconds` CLI parameter or the `DurationSeconds` API parameter to request a longer session. The `MaxSessionDuration` setting determines the maximum duration of the role session that can be requested using the `DurationSeconds` parameter. If users don't specify a value for the `DurationSeconds` parameter, their security credentials are valid for one hour.

**To change the maximum session duration setting for roles that are assumed using the AWS CLI (AWS CLI)**

1. (Optional) To view the current maximum session duration setting for a role, run the following command:
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. To update a role's maximum session duration setting, run the following command with the `max-session-duration` CLI parameter or the `MaxSessionDuration` API parameter:
   + [aws iam update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html)

   Your changes don't take effect until the next time someone assumes this role. To learn how to revoke existing sessions for this role, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md).

### Updating the maximum role session duration (AWS API)


**Note**  
Anyone who assumes the role from the AWS CLI or API can use the `duration-seconds` CLI parameter or the `DurationSeconds` API parameter to request a longer session. The `MaxSessionDuration` setting determines the maximum duration of the role session that can be requested using the `DurationSeconds` parameter. If users don't specify a value for the `DurationSeconds` parameter, their security credentials are valid for one hour.

**To change the maximum session duration setting for roles that are assumed using the API (AWS API)**

1. (Optional) To view the current maximum session duration setting for a role, call the following operation:
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. To update a role's maximum session duration setting, call the following operation with the `max-sessionduration` CLI parameter or the `MaxSessionDuration` API parameter:
   + [UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html)

   Your changes don't take effect until the next time someone assumes this role. To learn how to revoke existing sessions for this role, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md).

# Delete roles or instance profiles


If you no longer need a role, we recommend that you delete the role and its associated permissions. That way you don't have an unused entity that is not actively monitored or maintained. 

If the role was associated with an EC2 instance, you can also remove the role from the instance profile and then delete the instance profile.

**Warning**  
Make sure that you do not have any Amazon EC2 instances running with the role or instance profile you are about to delete. Deleting a role or instance profile that is associated with a running instance will break any applications that are running on the instance.

If you prefer not to permanently delete a role, you can disable a role. To do this, change the role policies and then revoke all current sessions. For example, you could add a policy to the role that denied access to all of AWS. You could also edit the trust policy to deny access to anyone attempting to assume the role. For more information about revoking sessions, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md).

**Topics**
+ [

## Viewing role access
](#roles-delete_prerequisites)
+ [

## Deleting a service-linked role
](#id_roles_manage_delete_slr)
+ [

## Deleting an IAM role (console)
](#roles-managingrole-deleting-console)
+ [

## Deleting an IAM role (AWS CLI)
](#roles-managingrole-deleting-cli)
+ [

## Deleting an IAM role (AWS API)
](#roles-managingrole-deleting-api)
+ [

## Related information
](#roles-managingrole-deleting-related-info)

## Viewing role access


Before you delete a role, we recommend that you review when the role was last used. You can do this using the AWS Management Console, the AWS CLI, or the AWS API. You should view this information because you don't want to remove access from someone using the role. 

The date of the role last activity might not match the last date reported in the **Last Accessed** tab. The [**Last Accessed**](access_policies_last-accessed-view-data.md) tab reports activity only for services allowed by the role permissions policies. The date of the role last activity includes the last attempt to access any service in AWS.

**Note**  
The tracking period for a role last activity and Last Accessed data is for the trailing 400 days. This period can be shorter if your Region began supporting these features within the last year. The role might have been used more than 400 days ago. For more information about the tracking period, see [Where AWS tracks last accessed information](access_policies_last-accessed.md#last-accessed_tracking-period).

**To view when a role was last used (console)**

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, choose **Roles**.

1. Find the row of the role with the activity you want to view. You can use the search field to narrow the results. View the **Last activity** column to see the number of days since the role was last used. If the role has not been used within the tracking period, then the table displays **None**. 

1. Choose the name of the role to view more information. The role ** Summary** page also includes **Last activity**, which displays the last used date for the role. If the role has not been used within the last 400 days, then **Last activity** displays **Not accessed in the tracking period**.

**To view when a role was last used (AWS CLI)**  
`[aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)` - Run this command to return information about a role, including the `RoleLastUsed` object. This object contains the `LastUsedDate` and the `Region` in which the role was last used. If `RoleLastUsed` is present but does not contain a value, then the role has not been used within the tracking period.

**To view when a role was last used (AWS API)**  
`[GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/GetRole.html)` - Call this operation to return information about a role, including the `RoleLastUsed` object. This object contains the `LastUsedDate` and the `Region` in which the role was last used. If `RoleLastUsed` is present but does not contain a value, then the role has not been used within the tracking period.

## Deleting a service-linked role


The method that you use to delete a service-linked role depends on the service. In some cases, you don't need to manually delete a service-linked role. For example, when you complete a specific action (such as removing a resource) in the service, the service might delete the service-linked role for you. In other cases, the service might support deleting a service-linked role manually from the service console, API, or AWS CLI. 

Review the documentation for the *[service-linked role](id_roles.md#iam-term-service-linked-role)* in the linked service to learn how to delete the role. You can view the service-linked roles in your account by going to the IAM **Roles** page in the console. Service-linked roles appear with **(Service-linked role)** in the **Trusted entities** column of the table. A banner on the role **Summary** page also indicates that the role is a service-linked role.

If the service does not include documentation for deleting the service-linked role, you can use the IAM console, AWS CLI, or API to delete the role.

## Deleting an IAM role (console)


When you use the AWS Management Console to delete a role, IAM automatically detaches managed policies associated with the role. It also automatically deletes any inline policies associated with the role, and any Amazon EC2 instance profile that contains the role. 

**Important**  
In some cases, a role might be associated with an Amazon EC2 instance profile, and the role and the instance profile might have the same name. In that case you can use the AWS Management Console to delete the role and the instance profile. This linkage happens automatically for roles and instance profiles that you create in the console. If you created the role from the AWS CLI, Tools for Windows PowerShell, or the AWS API, then the role and the instance profile might have different names. In that case you cannot use the console to delete them. Instead, you must use the AWS CLI, Tools for Windows PowerShell, or AWS API to first remove the role from the instance profile. You must then take a separate step to delete the role.

**To delete a role (console)**

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, choose **Roles**, and then select the check box next to the role name that you want to delete. 

1. At the top of the page, choose **Delete**.

1. In the confirmation dialog box, review the last accessed information, which shows when each of the selected roles last accessed an AWS service. This helps you to confirm if the role is currently active. If you want to proceed, enter the name of the role in the text input field and choose **Delete**. If you are sure, you can proceed with the deletion even if the last accessed information is still loading.

**Note**  
You cannot use the console to delete an instance profile unless it has the same name as the role. The instance profile is deleted as part of the process of deleting a role as described in the preceding procedure. To delete an instance profile without also deleting the role, you must use the AWS CLI or AWS API. For more information, see the following sections.

## Deleting an IAM role (AWS CLI)


When you use the AWS CLI to delete a role, you must first delete inline policies associated with the role. You must also detach managed policies associated with the role. If you want to delete the associated instance profile that contains the role, you must delete it separately.

**To delete a role (AWS CLI)**

1. If you don't know the name of the role that you want to delete, enter the following command to list the roles in your account:

   ```
   aws iam list-roles
   ```

   The list includes the Amazon Resource Name (ARN) of each role. Use the role name, not the ARN, to refer to roles with the CLI commands. For example, if a role has the following ARN: `arn:aws:iam::123456789012:role/myrole`, you refer to the role as **myrole**.

1. Remove the role from all instance profiles that the role is associated with.

   1. To list all instance profiles that the role is associated with, enter the following command:

      ```
      aws iam list-instance-profiles-for-role --role-name role-name
      ```

   1. To remove the role from an instance profile, enter the following command for each instance profile:

      ```
      aws iam remove-role-from-instance-profile --instance-profile-name instance-profile-name --role-name role-name
      ```

1. Delete all policies that are associated with the role.

   1. To list all inline policies that are in the role, enter the following command:

      ```
      aws iam list-role-policies --role-name role-name
      ```

   1. To delete each inline policy from the role, enter the following command for each policy: 

      ```
      aws iam delete-role-policy --role-name role-name --policy-name policy-name
      ```

   1. To list all managed policies that are attached to the role, enter the following command:

      ```
      aws iam list-attached-role-policies --role-name role-name
      ```

   1. To detach each managed policy from the role, enter the following command for each policy: 

      ```
      aws iam detach-role-policy --role-name role-name --policy-arn policy-arn
      ```

1. Enter the following command to delete the role:

   ```
   aws iam delete-role --role-name role-name
   ```

1. If you do not plan to reuse the instance profiles that were associated with the role, you can enter the following command to delete them:

   ```
   aws iam delete-instance-profile --instance-profile-name instance-profile-name
   ```

## Deleting an IAM role (AWS API)


When you use the IAM API to delete a role, you must first delete inline policies associated with the role. You must also detach managed policies associated with the role. If you want to delete the associated instance profile that contains the role, you must delete it separately.

**To delete a role (AWS API)**

1. To list all instance profiles that a role is associated with, call [ListInstanceProfilesForRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html).

   To remove the role from an instance profile, call [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html). You must pass the role name and instance profile name. 

   If you are not going to reuse an instance profile that was associated with the role, call [DeleteInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html) to delete it.

1. To list all inline policies for a role, call [ListRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRolePolicies.html).

   To delete inline policies that are associated with the role, call [DeleteRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRolePolicy.html). You must pass the role name and inline policy name. 

1. To list all managed policies that are attached to a role, call [ListAttachedRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedRolePolicies.html). 

   To detach managed policies that are attached to the role, call [DetachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachRolePolicy.html). You must pass the role name and managed policy ARN. 

1. Call [DeleteRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRole.html) to delete the role.

## Related information


For general information about instance profiles, see [Use instance profiles](id_roles_use_switch-role-ec2_instance-profiles.md).

For general information about service-linked roles, see [Create a service-linked role](id_roles_create-service-linked-role.md).

# Methods to assume a role
Methods to assume a role

Before a user, application, or service can use a role that you created, you must [grant permissions to switch](id_roles_use_permissions-to-switch.md) to the role. You can use any policy attached to groups or users to grant the necessary permissions. After permissions are granted, the user can assume a role from the AWS Management Console, the Tools for Windows PowerShell, the AWS Command Line Interface (AWS CLI) and the [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API.

**Important**  
When you create a role programmatically instead of in the IAM console, you have an option to add a `Path` of up to 512 characters in addition to the `RoleName`, which can be up to 64 characters long. However, if you intend to use a role with the **Switch Role** feature in the AWS Management Console, then the combined `Path` and `RoleName` cannot exceed 64 characters.

The method used to assume the role determines who can assume the role and how long the role session can last. When using `AssumeRole*` API operations, the IAM role that you assume is the resource. The user or role that calls `AssumeRole*` API operations is the principal.

The following table compares methods for assuming roles.


|  Method of assuming the role |  **Who can assume the role**  | **Method to specify credential lifetime** |  **Credential lifetime (min \$1 max \$1 default)**  | 
| --- | --- | --- | --- | 
| AWS Management Console | User or roles¹(by [switching roles](id_roles_use_switch-role-console.md)) | Maximum session duration on the Role Summary page | 15m \$1 Maximum session duration setting² \$1 1hr | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation |  User or role¹ | duration-seconds CLI or DurationSeconds API parameter | 15m \$1 Maximum session duration setting² \$1 1hr  | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API operation | Any user authenticated using SAML | duration-seconds CLI or DurationSeconds API parameter | 15m \$1 Maximum session duration setting² \$1 1hr  | 
| [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) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation | Any user authenticated using an OIDC provider | duration-seconds CLI or DurationSeconds API parameter | 15m \$1 Maximum session duration setting² \$1 1hr  | 
| [Console URL](id_roles_providers_enable-console-custom-url.md) constructed with AssumeRole  | User or role | SessionDuration HTML parameter in the URL | 15m \$1 12hr \$1 1hr  | 
| [Console URL](id_roles_providers_enable-console-custom-url.md) constructed with AssumeRoleWithSAML  | Any user authenticated using SAML | SessionDuration HTML parameter in the URL | 15m \$1 12hr \$1 1hr | 
| [Console URL](id_roles_providers_enable-console-custom-url.md) constructed with AssumeRoleWithWebIdentity  | Any user authenticated using an OIDC provider | SessionDuration HTML parameter in the URL | 15m \$1 12hr \$1 1hr  | 

¹ Using the credentials from one role to assume a different role is called [role chaining](id_roles.md#iam-term-role-chaining). When you use role chaining, the role's session duration is limited to one hour. This applies to AWS Management Console role switching, AWS CLI, and API operations. This limitation does not apply to the initial assumption of a role from user credentials, or to applications running on Amazon EC2 instances using instance profiles.

² This setting can have a value from 1 hour to 12 hours. For details about modifying the maximum session duration setting, see [IAM role management](id_roles_manage.md). This setting determines the maximum session duration that you can request when you get the role credentials. For example, when you use the [AssumeRole\$1](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operations to assume a role, you can specify a session length using the `DurationSeconds` parameter. Use this parameter to specify the length of the role session from 900 seconds (15 minutes) up to the maximum session duration setting for the role. IAM users who switch roles in the console are granted the maximum session duration, or the remaining time in their user session, whichever is less. Assume that you set a maximum duration of 5 hours on a role. An IAM user that has been signed into the console for 10 hours (out of the default maximum of 12) switches to the role. The available role session duration is 2 hours. To learn how to view the maximum value for your role, see [Update the maximum session duration for a role](id_roles_update-role-settings.md#id_roles_update-session-duration) later in this page.

**Notes**  
The maximum session duration setting does not limit sessions that are assumed by AWS services.
Amazon EC2 IAM role credentials are not subject to the maximum session duration configured in the role.
To allow users to assume the current role again within a role session, specify the role ARN or AWS account ARN as a principal in the role trust policy. AWS services that provide compute resources such as Amazon EC2, Amazon ECS, Amazon EKS, and Lambda provide temporary credentials and automatically update these credentials. This ensures that you always have a valid set of credentials. For these services, it's not necessary to assume the current role again to obtain temporary credentials. However, if you intend to pass [session tags](id_session-tags.md) or a [session policy](access_policies.md#policies_session), you need to assume the current role again. To learn how to modify a role trust policy to add the principal role ARN or AWS account ARN, see [Update a role trust policy](id_roles_update-role-trust-policy.md).

**Topics**
+ [

# Switch from a user to an IAM role (console)
](id_roles_use_switch-role-console.md)
+ [

# Switch to an IAM role (AWS CLI)
](id_roles_use_switch-role-cli.md)
+ [

# Switch to an IAM role (Tools for Windows PowerShell)
](id_roles_use_switch-role-twp.md)
+ [

# Switch to an IAM role (AWS API)
](id_roles_use_switch-role-api.md)
+ [

# Use an IAM role to grant permissions to applications running on Amazon EC2 instances
](id_roles_use_switch-role-ec2.md)
+ [

# Use instance profiles
](id_roles_use_switch-role-ec2_instance-profiles.md)

# Switch from a user to an IAM role (console)
Switch from a user to a role

You can switch roles when you sign in as an IAM user, a user in IAM Identity Center, a SAML-federated role, or a web-identity federated role. A *role* specifies a set of permissions that you can use to access AWS resources that you need. However, you don't sign in to a role, but once signed in as an IAM user you can switch to an IAM role. This temporarily sets aside your original user permissions and instead gives you the permissions assigned to the role. The role can be in your own account or any other AWS account. For more information about roles, their benefits, and how to create them, see [IAM roles](id_roles.md), and [IAM role creation](id_roles_create.md).

The permissions of your user and any roles that you switch to aren't cumulative. Only one set of permissions is active at a time. When you switch to a role, you temporarily give up your user permissions and work with the permissions that are assigned to the role. When you exit the role, your user permissions are automatically restored.

When you switch roles in the AWS Management Console, the console always uses your original credentials to authorize the switch. For example, if you switch to RoleA, IAM uses your original credentials to determine whether you are allowed to assume RoleA. If you then switch to RoleB *while you are using RoleA*, AWS still uses your **original** credentials to authorize the switch, not the credentials for RoleA.

**Note**  
When you sign in as a user in IAM Identity Center, as a SAML-federated role, or as a web-identity federated role you assume an IAM role when you start your session. For example, when a user in IAM Identity Center signs in to the AWS access portal they must choose a permission set that correlates to a role before they can access AWS resources.

## Role sessions


When you switch roles, your AWS Management Console session lasts for 1 hour by default. IAM user sessions are 12 hours by default, other users might have different session durations defined. When you switch roles in the console, you are granted the role maximum session duration, or the remaining time in your user session, whichever is less. You can't extend your session duration by assuming a role.

For example, assume that a maximum session duration of 10 hours is set for a role. You have been signed in to the console for 8 hours when you decide to switch to the role. There are 4 hours remaining in your user session, so the allowed role session duration is 4 hours, not the maximum session duration of 10 hours. The following table shows how to determine the session duration for an IAM user when switching roles in the console.


| IAM user session time remaining is… | Role session duration is… | 
| --- | --- | 
| Less than role maximum session duration | Time remaining in user session | 
| Greater than role maximum session duration | Maximum session duration value | 
| Equal to role maximum session duration | Maximum session duration value (approximate) | 

Using the credentials from one role to assume a different role is called [role chaining](id_roles.md#iam-term-role-chaining). When you use role chaining, the session duration is limited to one hour, regardless of the maximum session duration setting configured for individual roles. This applies to AWS Management Console role switching, AWS CLI, and API operations.

**Note**  
Some AWS service consoles can autorenew your role session when it expires without you taking any action. Some might prompt you to reload your browser page to reauthenticate your session.

## Considerations

+ You can't switch roles if you sign in as the AWS account root user. 
+ Users must be granted permission to switch roles by policy. For instructions, see [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md).
+ You can't switch roles in the AWS Management Console to a role that requires an [ExternalId](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) value. You can switch to such a role only by calling the [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API that supports the `ExternalId` parameter.

## To switch to a role


1. Follow the sign-in procedure appropriate to you user type as described in [Sign in to the AWS Management Console](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

1. In the AWS Management Console, choose your user name on the navigation bar in the upper right. It typically looks like this: ***username*@*account\$1ID\$1number\$1or\$1alias***.

1. Select one of the following methods to switch roles:
   + Choose **Switch role**.
   + If you have opted in to multi-session support, choose **Add session** and select **Switch role**.
**Note**  
You can sign in to up to five different identities simultaneously in a single web browser in the AWS Management Console. For details, see [Signing in to multiple accounts](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/multisession.html) in the *AWS Management Console Getting Started Guide*.

1. On the **Switch Role** page, type the account ID number or the account alias and the name of the role that was provided by your administrator.
**Note**  
If your administrator created the role with a path, such as `division_abc/subdivision_efg/roleToDoX`, then you must type that complete path and name in the **Role** box. If you type only the role name, or if the combined `Path` and `RoleName` exceed 64 characters, the role switch fails. This is a limit of the browser cookies that store the role name. If this happens, contact your administrator and ask them to reduce the size of the path and role name.

1. (Optional)You can enter a display name and select a display color that will highlight the role in the console navigation bar.
   + For **Display name**, type text that you want to appear on the navigation bar in place of your user name when this role is active. A name is suggested, based on the account and role information, but you can change it to whatever has meaning for you. 
   + For **Display color**, select a color to highlight the display name.

   The name and color can help remind you when this role is active, which changes your permissions. For example, for a role that gives you access to the test environment, you might specify a **Display name** of **Test** and select the green **Color**. For the role that gives you access to production, you might specify a **Display name** of **Production** and select red as the **Color**.

1. Choose **Switch Role**. The display name and color replace your user name on the navigation bar, and you can start using the permissions that the role grants you.

1. After you have completed the tasks that require the IAM role you can switch back to your original session. This will remove the additional permissions provided by the role and return you to your standard permissions.

   1. In the IAM console, choose your role's **Display name** on the navigation bar in the upper right.

   1. Choose **Switch back**.

      For example, assume you are signed in to account number `123456789012` using the user name `Richard`. After you use the `admin-role` role, you want to stop using the role and return to your original permissions. To stop using the role, you choose **admin-role @ 123456789012**, and then choose **Switch back**.  
![\[Graphic locating the Switch back function to stop using an IAM role and return to the original user.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/role-stop-using.png)

**Tip**  
The last several roles that you used appear on the menu. The next time you want to switch to one of those roles, you can simply choose the role you want. You are only required to type the account and role information manually if the role isn't displayed on the menu.

## Additional resources

+ [Grant a user permissions to switch roles](id_roles_use_permissions-to-switch.md)
+ [Grant a user permissions to pass a role to an AWS service](id_roles_use_passrole.md)
+ [Create a role to give permissions to an IAM user](id_roles_create_for-user.md)
+ [Create a role to delegate permissions to an AWS service](id_roles_create_for-service.md)
+ [Troubleshoot IAM roles](troubleshoot_roles.md)

# Switch to an IAM role (AWS CLI)
Switch roles (AWS CLI)

A *role* specifies a set of permissions that you can use to access AWS resources that you need. In that sense, it is similar to a [user in AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) (IAM). When you sign in as a user, you get a specific set of permissions. However, you don't sign in to a role, but after signing in as a user, you can switch to a role. This temporarily sets aside your original user permissions and instead gives you the permissions assigned to the role. The role can be in your own account or any other AWS account. For more information about roles, their benefits, and how to create and configure them, see [IAM roles](id_roles.md), and [IAM role creation](id_roles_create.md). To learn about the different methods that you can use to assume a role, see [Methods to assume a role](id_roles_manage-assume.md).

**Important**  
The permissions of your IAM user and any roles that you assume are not cumulative. Only one set of permissions is active at a time. When you assume a role, you temporarily give up your previous user or role permissions and work with the permissions that are assigned to the role. When you exit the role, your user permissions are automatically restored.

You can use a role to run an AWS CLI command when you are signed in as an IAM user. You can also use a role to run an AWS CLI command when you are signed in as an [externally authenticated user](id_roles_providers.md) ([SAML](id_roles_providers_saml.md) or [OIDC](id_roles_providers_oidc.md)) that is already using a role. In addition, you can use a role to run an AWS CLI command from within an Amazon EC2 instance that is attached to a role through its instance profile. You cannot assume a role when you are signed in as the AWS account root user.

[**Role chaining**](id_roles.md#iam-term-role-chaining) – You can also use role chaining, which is using permissions from a role to access a second role.

By default, your role session lasts for one hour. When you assume this role using the `assume-role*` CLI operations, you can specify a value for the `duration-seconds` parameter. This value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. If you switch roles in the console, your session duration is limited to maximum of one hour. To learn how to view the maximum value for your role, see [Update the maximum session duration for a role](id_roles_update-role-settings.md#id_roles_update-session-duration). 

If you use role chaining, your session duration is limited to a maximum of one hour. If you then use the `duration-seconds` parameter to provide a value greater than one hour, the operation fails.

## Example scenario: Switch to a production role


Imagine that you are an IAM user for working in the development environment. In this scenario, you occasionally need to work with the production environment at the command line with the [AWS CLI](http://aws.amazon.com/cli/). You already have an access key credential set available to you. This can be the access key pair that is assigned to your standard IAM user. Or, if you signed in as a SAML or OIDC federated principal, it can be the access key pair for the role that was initially assigned to you. If your current permissions grant you the ability to assume a specific IAM role, then you can identify that role in a "profile" in the AWS CLI configuration files. That command is then run with the permissions of the specified IAM role, not the original identity. Note that when you specify that profile in an AWS CLI command, you are using the new role. In this situation, you cannot make use of your original permissions in the development account at the same time. The reason is that only one set of permissions can be in effect at a time.

**Note**  
For security purposes, administrators can [review AWS CloudTrail logs](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds) to learn who performed an action in AWS. Your administrator might require that you specify a source identity or a role session name when you assume the role. For more information, see [`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity) and [`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname).

**To switch to a production role (AWS CLI)**

1. <a name="step-configure-default"></a>If you have never used the AWS CLI, then you must first configure your default CLI profile. Open a command prompt and set up your AWS CLI installation to use the access key from your IAM user or from your federated role. For more information, see [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-quick-configuration) in the *AWS Command Line Interface User Guide*.

   Run the [aws configure](https://docs.aws.amazon.com/cli/latest/reference/configure/) command as follows:

   ```
   aws configure
   ```

   When prompted, provide the following information:

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

1. Create a new profile for the role in the `.aws/config` file in Unix or Linux, or the `C:\Users\USERNAME\.aws\config` file in Windows. The following example creates a profile called `prodaccess` that switches to the role `ProductionAccessRole` in the `123456789012` account. You get the role ARN from the account administrator who created the role. When this profile is invoked, the AWS CLI uses the credentials of the `source_profile` to request credentials for the role. Because of that, the identity referenced as the `source_profile` must have `sts:AssumeRole` permissions to the role that is specified in the `role_arn`.

   ```
   [profile prodaccess]
       role_arn = arn:aws:iam::123456789012:role/ProductionAccessRole
       source_profile = default
   ```

1. After you create the new profile, any AWS CLI command that specifies the parameter `--profile prodaccess` runs under the permissions that are attached to the IAM role `ProductionAccessRole` instead of the default user.

   ```
   aws iam list-users --profile prodaccess
   ```

   This command works if the permissions assigned to the `ProductionAccessRole` enable listing the users in the current AWS account.

1. To return to the permissions granted by your original credentials, run commands without the `--profile` parameter. The AWS CLI reverts to using the credentials in your default profile, which you configured in [Step 1](#step-configure-default).

For more information, see [Assuming a Role](https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html) in the *AWS Command Line Interface User Guide*.

## Example scenario: Allow an instance profile role to switch to a role in another account


Imagine that you are using two AWS accounts, and you want to allow an application running on an Amazon EC2 instance to run [AWS CLI](http://aws.amazon.com/cli/) commands in both accounts. Assume that the EC2 instance exists in account `111111111111`. That instance includes the `abcd` instance profile role that allows the application to perform read-only Amazon S3 tasks on the `amzn-s3-demo-bucket1` bucket within the same `111111111111` account. However, the application must also be allowed to assume the `efgh` cross-account role to perform tasks in account `222222222222`. To do this, the `abcd` EC2 instance profile role must have the following permissions policy:

***Account 111111111111 `abcd` role permissions policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1/*",
                "arn:aws:s3:::amzn-s3-demo-bucket1"
            ]
        },
        {
            "Sid": "AllowIPToAssumeCrossAccountRole",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::222222222222:role/efgh"
        }
    ]
}
```

------

Assume that the `efgh` cross-account role allows read-only Amazon S3 tasks on the `amzn-s3-demo-bucket2` bucket within the same `222222222222` account. To do this, the `efgh` cross-account role must have the following permissions policy:

***Account 222222222222 `efgh` role permissions policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket2/*",
                "arn:aws:s3:::amzn-s3-demo-bucket2"
            ]
        }
    ]
}
```

------

The `efgh` role must allow the `abcd` instance profile role to assume it. To do this, the `efgh` role must have the following trust policy:

***Account 222222222222 `efgh` role trust policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "efghTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"AWS": "arn:aws:iam::111111111111:role/abcd"}
        }
    ]
}
```

------

To then run AWS CLI commands in account `222222222222`, you must update the CLI configuration file. Identify the `efgh` role as the "profile" and the `abcd` EC2 instance profile role as the "credential source" in the AWS CLI configuration file. Then your CLI commands are run with the permissions of the `efgh` role, not the original `abcd` role.

**Note**  
For security purposes, you can use AWS CloudTrail to audit the use of roles in the account. To differentiate between role sessions when a role is used by different principals in CloudTrail logs, you can use the role session name. When the AWS CLI assumes a role on a user's behalf as described in this topic, a role session name is automatically created as `AWS-CLI-session-nnnnnnnn`. Here *nnnnnnnn* is an integer that represents the time in [Unix epoch time](http://wikipedia.org/wiki/Unix_time) (the number of seconds since midnight UTC on January 1, 1970). For more information, see [CloudTrail Event Reference](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/eventreference.html) in the *AWS CloudTrail User Guide*.

**To allow an EC2 instance profile role to switch to a cross-account role (AWS CLI)**

1. You do not have to configure a default CLI profile. Instead, you can load credentials from the EC2 instance profile metadata. Create a new profile for the role in the `.aws/config` file. The following example creates an `instancecrossaccount` profile that switches to the role `efgh` in the `222222222222` account. When this profile is invoked, the AWS CLI uses the credentials of the EC2 instance profile metadata to request credentials for the role. Because of that, the EC2 instance profile role must have `sts:AssumeRole` permissions to the role specified in the `role_arn`.

   ```
   [profile instancecrossaccount]
   role_arn = arn:aws:iam::222222222222:role/efgh
   credential_source = Ec2InstanceMetadata
   ```

1. After you create the new profile, any AWS CLI command that specifies the parameter `--profile instancecrossaccount` runs under the permissions that are attached to the `efgh` role in account `222222222222`.

   ```
   aws s3 ls amzn-s3-demo-bucket2 --profile instancecrossaccount
   ```

   This command works if the permissions that are assigned to the `efgh` role allow listing the users in the current AWS account.

1. To return to the original EC2 instance profile permissions in account `111111111111`, run the CLI commands without the `--profile` parameter.

For more information, see [Assuming a Role](https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html) in the *AWS Command Line Interface User Guide*.

# Switch to an IAM role (Tools for Windows PowerShell)
Switch roles (Tools for Windows PowerShell)

A *role* specifies a set of permissions that you can use to access AWS resources that you need. In that sense, it is similar to a [user in AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) (IAM). When you sign in as a user, you get a specific set of permissions. However, you don't sign in to a role, but once signed in you can switch to a role. This temporarily sets aside your original user permissions and instead gives you the permissions assigned to the role. The role can be in your own account or any other AWS account. For more information about roles, their benefits, and how to create and configure them, see [IAM roles](id_roles.md), and [IAM role creation](id_roles_create.md).

**Important**  
The permissions of your IAM user and any roles that you switch to are not cumulative. Only one set of permissions is active at a time. When you switch to a role, you temporarily give up your user permissions and work with the permissions that are assigned to the role. When you exit the role, your user permissions are automatically restored.

This section describes how to switch roles when you work at the command line with the AWS Tools for Windows PowerShell.

Imagine that you have an account in the development environment and you occasionally need to work with the production environment at the command line using the [Tools for Windows PowerShell](http://aws.amazon.com/powershell/). You already have one access key credential set available to you. These can be an access key pair assigned to your standard IAM user. Or, if you signed-in as a SAML or OIDC federated principal, they can be the access key pair for the role initially assigned to you. You can use these credentials to run the `Use-STSRole` cmdlet that passes the ARN of a new role as a parameter. The command returns temporary security credentials for the requested role. You can then use those credentials in subsequent PowerShell commands with the role's permissions to access resources in production. While you use the role, you cannot use your user permissions in the Development account because only one set of permissions is in effect at a time.

**Note**  
For security purposes, administrators can [review AWS CloudTrail logs](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds) to learn who performed an action in AWS. Your administrator might require that you specify a source identity or a role session name when you assume the role. For more information, see [`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity) and [`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname).

Note that all access keys and tokens are examples only and cannot be used as shown. Replace with the appropriate values from your live environment.

**To switch to a role (Tools for Windows PowerShell)**

1. Open a PowerShell command prompt and configure the default profile to use the access key from your current IAM user or from your federated role. If you have previously used the Tools for Windows PowerShell, then this is likely already done. Note that you can switch roles only if you are signed in as an IAM user, not the AWS account root user.

   ```
   PS C:\> Set-AWSCredentials -AccessKey AKIAIOSFODNN7EXAMPLE -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY -StoreAs MyMainUserProfile
   PS C:\> Initialize-AWSDefaults -ProfileName MyMainUserProfile -Region us-east-2
   ```

   For more information, see [Using AWS Credentials](https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html) in the *AWS Tools for PowerShell User Guide*.

1. To retrieve credentials for the new role, run the following command to switch to the `RoleName` role in the 123456789012 account. You get the role ARN from the account administrator who created the role. The command requires that you provide a session name as well. You can choose any text for that. The following command requests the credentials and then captures the `Credentials` property object from the returned results object and stores it in the `$Creds` variable.

   ```
   PS C:\> $Creds = (Use-STSRole -RoleArn "arn:aws:iam::123456789012:role/RoleName" -RoleSessionName "MyRoleSessionName").Credentials
   ```

   `$Creds` is an object that now contains the `AccessKeyId`, `SecretAccessKey`, and `SessionToken` elements that you need in the following steps. The following sample commands illustrate typical values:

   ```
   PS C:\> $Creds.AccessKeyId
   AKIAIOSFODNN7EXAMPLE
   
   PS C:\> $Creds.SecretAccessKey
   wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   
   PS C:\> $Creds.SessionToken
   AQoDYXdzEGcaEXAMPLE2gsYULo+Im5ZEXAMPLEeYjs1M2FUIgIJx9tQqNMBEXAMPLECvSRyh0FW7jEXAMPLEW+vE/7s1HRp
   XviG7b+qYf4nD00EXAMPLEmj4wxS04L/uZEXAMPLECihzFB5lTYLto9dyBgSDyEXAMPLE9/g7QRUhZp4bqbEXAMPLENwGPy
   Oj59pFA4lNKCIkVgkREXAMPLEjlzxQ7y52gekeVEXAMPLEDiB9ST3UuysgsKdEXAMPLE1TVastU1A0SKFEXAMPLEiywCC/C
   s8EXAMPLEpZgOs+6hz4AP4KEXAMPLERbASP+4eZScEXAMPLEsnf87eNhyDHq6ikBQ==
   
   PS C:\> $Creds.Expiration
   Thursday, June 18, 2018 2:28:31 PM
   ```

1. To use these credentials for any subsequent command, include them with the `-Credential` parameter. For example, the following command uses the credentials from the role and works only if the role is granted the `iam:ListRoles` permission and can therefore run the `Get-IAMRoles` cmdlet:

   ```
           PS C:\> get-iamroles -Credential $Creds
   ```

1. To return to your original credentials, simply stop using the `-Credentials $Creds` parameter and allow PowerShell to revert to the credentials that are stored in the default profile.

# Switch to an IAM role (AWS API)
Switch roles (AWS API)

A *role* specifies a set of permissions that you can use to access AWS resources. In that sense, it is similar to an [IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html). A principal (person or application) assumes a role to receive temporary permissions to carry out required tasks and interact with AWS resources. The role can be in your own account or any other AWS account. For more information about roles, their benefits, and how to create and configure them, see [IAM roles](id_roles.md), and [IAM role creation](id_roles_create.md). To learn about the different methods that you can use to assume a role, see [Methods to assume a role](id_roles_manage-assume.md).

**Important**  
The permissions of your IAM user and any roles that you assume are not cumulative. Only one set of permissions is active at a time. When you assume a role, you temporarily give up your previous user or role permissions and work with the permissions that are assigned to the role. When you exit the role, your original permissions are automatically restored.

To assume a role, an application calls the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation and passes the ARN of the role to use. The operation creates a new session with temporary credentials. This session has the same permissions as the identity-based policies for that role. 

When you call [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html), you can optionally pass inline or managed [session policies](access_policies.md#policies_session). Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary credential session for a role or federated user session. You can pass a single JSON inline session policy document using the `Policy` parameter. You can use the `PolicyArns` parameter to specify up to 10 managed session policies. The resulting session's permissions are the intersection of the entity's identity-based policies and the session policies. Session policies are useful when you need to give the role's temporary credentials to someone else. They can use the role's temporary credentials in subsequent AWS API calls to access resources in the account that owns the role. You cannot use session policies to grant more permissions than those allowed by the identity-based policy. To learn more about how AWS determines the effective permissions of a role, see [Policy evaluation logic](reference_policies_evaluation-logic.md). 

![\[PermissionsWhenPassingRoles_Diagram\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/role_passed_policy_permissions.png)


You can call `AssumeRole` when you are signed in as an IAM user, or as an [externally authenticated user](id_roles_providers.md) ([SAML](id_roles_providers_saml.md) or [OIDC](id_roles_providers_oidc.md)) already using a role. You can also use [*role chaining*](id_roles.md#iam-term-role-chaining), which is using a role to assume a second role. You cannot assume a role when you are signed in as the AWS account root user.

By default, your role session lasts for one hour. When you assume this role using the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operations, you can specify a value for the `DurationSeconds` parameter. This value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. To learn how to view the maximum value for your role, see [Update the maximum session duration for a role](id_roles_update-role-settings.md#id_roles_update-session-duration). 

If you use role chaining, your session is limited to a maximum of one hour. If you then use the `DurationSeconds` parameter to provide a value greater than one hour, the operation fails.

**Note**  
For security purposes, administrators can [review AWS CloudTrail logs](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds) to learn who performed an action in AWS. Your administrator might require that you specify a source identity or a role session name when you assume the role. For more information, see [`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity) and [`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname).

The following code examples show how to create a user and assume a role.

**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).
+ Create a user with no permissions.
+ Create a role that grants permission to list Amazon S3 buckets for the account.
+ Add a policy to let the user assume the role.
+ Assume the role and list S3 buckets using temporary credentials, then clean up resources.

------
#### [ .NET ]

**SDK for .NET**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples). 

```
global using Amazon.IdentityManagement;
global using Amazon.S3;
global using Amazon.SecurityToken;
global using IAMActions;
global using IamScenariosCommon;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;


namespace IAMActions;

public class IAMWrapper
{
    private readonly IAmazonIdentityManagementService _IAMService;

    /// <summary>
    /// Constructor for the IAMWrapper class.
    /// </summary>
    /// <param name="IAMService">An IAM client object.</param>
    public IAMWrapper(IAmazonIdentityManagementService IAMService)
    {
        _IAMService = IAMService;
    }

    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }


    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }


    /// <summary>
    /// Create a new IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="rolePolicyDocument">The name of the IAM policy document
    /// for the new role.</param>
    /// <returns>The Amazon Resource Name (ARN) of the role.</returns>
    public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument)
    {
        var request = new CreateRoleRequest
        {
            RoleName = roleName,
            AssumeRolePolicyDocument = rolePolicyDocument,
        };

        var response = await _IAMService.CreateRoleAsync(request);
        return response.Role.Arn;
    }


    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }


    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }


    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }


    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }


    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }


    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }


    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }


    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }


    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }


    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }


    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }


    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Add or update an inline policy document that is embedded in an IAM user.
    /// </summary>
    /// <param name="userName">The name of the IAM user.</param>
    /// <param name="policyName">The name of the IAM policy.</param>
    /// <param name="policyDocument">The policy document defining the IAM policy.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutUserPolicyAsync(string userName, string policyName, string policyDocument)
    {
        var request = new PutUserPolicyRequest
        {
            UserName = userName,
            PolicyName = policyName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutUserPolicyAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Wait for a new access key to be ready to use.
    /// </summary>
    /// <param name="accessKeyId">The Id of the access key.</param>
    /// <returns>A boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitUntilAccessKeyIsReady(string accessKeyId)
    {
        var keyReady = false;

        do
        {
            try
            {
                var response = await _IAMService.GetAccessKeyLastUsedAsync(
                    new GetAccessKeyLastUsedRequest { AccessKeyId = accessKeyId });
                if (response.UserName is not null)
                {
                    keyReady = true;
                }
            }
            catch (NoSuchEntityException)
            {
                keyReady = false;
            }
        } while (!keyReady);

        return keyReady;
    }
}



using Microsoft.Extensions.Configuration;

namespace IAMBasics;

public class IAMBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the AWS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonIdentityManagementService>()
            .AddTransient<IAMWrapper>()
            .AddTransient<UIWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<IAMBasics>();


        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // Values needed for user, role, and policies.
        string userName = configuration["UserName"]!;
        string s3PolicyName = configuration["S3PolicyName"]!;
        string roleName = configuration["RoleName"]!;


        var iamWrapper = host.Services.GetRequiredService<IAMWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        uiWrapper.DisplayBasicsOverview();
        uiWrapper.PressEnter();

        // First create a user. By default, the new user has
        // no permissions.
        uiWrapper.DisplayTitle("Create User");
        Console.WriteLine($"Creating a new user with user name: {userName}.");
        var user = await iamWrapper.CreateUserAsync(userName);
        var userArn = user.Arn;

        Console.WriteLine($"Successfully created user: {userName} with ARN: {userArn}.");
        uiWrapper.WaitABit(15, "Now let's wait for the user to be ready for use.");

        // Define a role policy document that allows the new user
        // to assume the role.
        string assumeRolePolicyDocument = "{" +
          "\"Version\": \"2012-10-17\"," +
          "\"Statement\": [{" +
              "\"Effect\": \"Allow\"," +
              "\"Principal\": {" +
              $"	\"AWS\": \"{userArn}\"" +
              "}," +
              "\"Action\": \"sts:AssumeRole\"" +
          "}]" +
        "}";

        // Permissions to list all buckets.
        string policyDocument = "{" +
            "\"Version\": \"2012-10-17\"," +
            "	\"Statement\" : [{" +
                "	\"Action\" : [\"s3:ListAllMyBuckets\"]," +
                "	\"Effect\" : \"Allow\"," +
                "	\"Resource\" : \"*\"" +
            "}]" +
        "}";

        // Create an AccessKey for the user.
        uiWrapper.DisplayTitle("Create access key");
        Console.WriteLine("Now let's create an access key for the new user.");
        var accessKey = await iamWrapper.CreateAccessKeyAsync(userName);

        var accessKeyId = accessKey.AccessKeyId;
        var secretAccessKey = accessKey.SecretAccessKey;

        Console.WriteLine($"We have created the access key with Access key id: {accessKeyId}.");

        Console.WriteLine("Now let's wait until the IAM access key is ready to use.");
        var keyReady = await iamWrapper.WaitUntilAccessKeyIsReady(accessKeyId);

        // Now try listing the Amazon Simple Storage Service (Amazon S3)
        // buckets. This should fail at this point because the user doesn't
        // have permissions to perform this task.
        uiWrapper.DisplayTitle("Try to display Amazon S3 buckets");
        Console.WriteLine("Now let's try to display a list of the user's Amazon S3 buckets.");
        var s3Client1 = new AmazonS3Client(accessKeyId, secretAccessKey);
        var stsClient1 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        var s3Wrapper = new S3Wrapper(s3Client1, stsClient1);
        var buckets = await s3Wrapper.ListMyBucketsAsync();

        Console.WriteLine(buckets is null
            ? "As expected, the call to list the buckets has returned a null list."
            : "Something went wrong. This shouldn't have worked.");

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Create IAM role");
        Console.WriteLine($"Creating the role: {roleName}");

        // Creating an IAM role to allow listing the S3 buckets. A role name
        // is not case sensitive and must be unique to the account for which it
        // is created.
        var roleArn = await iamWrapper.CreateRoleAsync(roleName, assumeRolePolicyDocument);

        uiWrapper.PressEnter();

        // Create a policy with permissions to list S3 buckets.
        uiWrapper.DisplayTitle("Create IAM policy");
        Console.WriteLine($"Creating the policy: {s3PolicyName}");
        Console.WriteLine("with permissions to list the Amazon S3 buckets for the account.");
        var policy = await iamWrapper.CreatePolicyAsync(s3PolicyName, policyDocument);

        // Wait 15 seconds for the IAM policy to be available.
        uiWrapper.WaitABit(15, "Waiting for the policy to be available.");

        // Attach the policy to the role you created earlier.
        uiWrapper.DisplayTitle("Attach new IAM policy");
        Console.WriteLine("Now let's attach the policy to the role.");
        await iamWrapper.AttachRolePolicyAsync(policy.Arn, roleName);

        // Wait 15 seconds for the role to be updated.
        Console.WriteLine();
        uiWrapper.WaitABit(15, "Waiting for the policy to be attached.");

        // Use the AWS Security Token Service (AWS STS) to have the user
        // assume the role we created.
        var stsClient2 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        // Wait for the new credentials to become valid.
        uiWrapper.WaitABit(10, "Waiting for the credentials to be valid.");

        var assumedRoleCredentials = await s3Wrapper.AssumeS3RoleAsync("temporary-session", roleArn);

        // Try again to list the buckets using the client created with
        // the new user's credentials. This time, it should work.
        var s3Client2 = new AmazonS3Client(assumedRoleCredentials);

        s3Wrapper.UpdateClients(s3Client2, stsClient2);

        buckets = await s3Wrapper.ListMyBucketsAsync();

        uiWrapper.DisplayTitle("List Amazon S3 buckets");
        Console.WriteLine("This time we should have buckets to list.");
        if (buckets is not null)
        {
            buckets.ForEach(bucket =>
            {
                Console.WriteLine($"{bucket.BucketName} created: {bucket.CreationDate}");
            });
        }

        uiWrapper.PressEnter();

        // Now clean up all the resources used in the example.
        uiWrapper.DisplayTitle("Clean up resources");
        Console.WriteLine("Thank you for watching. The IAM Basics demo is complete.");
        Console.WriteLine("Please wait while we clean up the resources we created.");

        await iamWrapper.DetachRolePolicyAsync(policy.Arn, roleName);

        await iamWrapper.DeletePolicyAsync(policy.Arn);

        await iamWrapper.DeleteRoleAsync(roleName);

        await iamWrapper.DeleteAccessKeyAsync(accessKeyId, userName);

        await iamWrapper.DeleteUserAsync(userName);

        uiWrapper.PressEnter();

        Console.WriteLine("All done cleaning up our resources. Thank you for your patience.");
    }
}


namespace IamScenariosCommon;

using System.Net;

/// <summary>
/// A class to perform Amazon Simple Storage Service (Amazon S3) actions for
/// the IAM Basics scenario.
/// </summary>
public class S3Wrapper
{
    private IAmazonS3 _s3Service;
    private IAmazonSecurityTokenService _stsService;

    /// <summary>
    /// Constructor for the S3Wrapper class.
    /// </summary>
    /// <param name="s3Service">An Amazon S3 client object.</param>
    /// <param name="stsService">An AWS Security Token Service (AWS STS)
    /// client object.</param>
    public S3Wrapper(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }

    /// <summary>
    /// Assumes an AWS Identity and Access Management (IAM) role that allows
    /// Amazon S3 access for the current session.
    /// </summary>
    /// <param name="roleSession">A string representing the current session.</param>
    /// <param name="roleToAssume">The name of the IAM role to assume.</param>
    /// <returns>Credentials for the newly assumed IAM role.</returns>
    public async Task<Credentials> AssumeS3RoleAsync(string roleSession, string roleToAssume)
    {
        // Create the request to use with the AssumeRoleAsync call.
        var request = new AssumeRoleRequest()
        {
            RoleSessionName = roleSession,
            RoleArn = roleToAssume,
        };

        var response = await _stsService.AssumeRoleAsync(request);

        return response.Credentials;
    }


    /// <summary>
    /// Delete an S3 bucket.
    /// </summary>
    /// <param name="bucketName">Name of the S3 bucket to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        var result = await _s3Service.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName });
        return result.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// List the buckets that are owned by the user's account.
    /// </summary>
    /// <returns>Async Task.</returns>
    public async Task<List<S3Bucket>?> ListMyBucketsAsync()
    {
        try
        {
            // Get the list of buckets accessible by the new user.
            var response = await _s3Service.ListBucketsAsync();

            return response.Buckets;
        }
        catch (AmazonS3Exception ex)
        {
            // Something else went wrong. Display the error message.
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Create a new S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name for the new bucket.</param>
    /// <returns>A Boolean value indicating whether the action completed
    /// successfully.</returns>
    public async Task<bool> PutBucketAsync(string bucketName)
    {
        var response = await _s3Service.PutBucketAsync(new PutBucketRequest { BucketName = bucketName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Update the client objects with new client objects. This is available
    /// because the scenario uses the methods of this class without and then
    /// with the proper permissions to list S3 buckets.
    /// </summary>
    /// <param name="s3Service">The Amazon S3 client object.</param>
    /// <param name="stsService">The AWS STS client object.</param>
    public void UpdateClients(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }
}


namespace IamScenariosCommon;

public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the IAM Groups scenario.
    /// </summary>
    public void DisplayGroupsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to the IAM Groups Demo");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates an Amazon Identity and Access Management (IAM) group.");
        Console.WriteLine("\t2. Adds an IAM policy to the IAM group giving it full access to Amazon S3.");
        Console.WriteLine("\t3. Creates a new IAM user.");
        Console.WriteLine("\t4. Creates an IAM access key for the user.");
        Console.WriteLine("\t5. Adds the user to the IAM group.");
        Console.WriteLine("\t6. Lists the buckets on the account.");
        Console.WriteLine("\t7. Proves that the user has full Amazon S3 access by creating a bucket.");
        Console.WriteLine("\t8. List the buckets again to show the new bucket.");
        Console.WriteLine("\t9. Cleans up all the resources created.");
    }

    /// <summary>
    /// Show information about the IAM Basics scenario.
    /// </summary>
    public void DisplayBasicsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to IAM Basics");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates a user with no permissions.");
        Console.WriteLine("\t2. Creates a role and policy that grant s3:ListAllMyBuckets permission.");
        Console.WriteLine("\t3. Grants the user permission to assume the role.");
        Console.WriteLine("\t4. Creates an S3 client object as the user and tries to list buckets (this will fail).");
        Console.WriteLine("\t5. Gets temporary credentials by assuming the role.");
        Console.WriteLine("\t6. Creates a new S3 client object with the temporary credentials and lists the buckets (this will succeed).");
        Console.WriteLine("\t7. Deletes all the resources.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title, and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
+ For API details, see the following topics in *AWS SDK for .NET API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Bash ]

**AWS CLI with Bash script**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples). 

```
###############################################################################
# function iam_create_user_assume_role
#
# Scenario to create an IAM user, create an IAM role, and apply the role to the user.
#
#     "IAM access" permissions are needed to run this code.
#     "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
#           create a custom policy).
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function iam_create_user_assume_role() {
  {
    if [ "$IAM_OPERATIONS_SOURCED" != "True" ]; then

      source ./iam_operations.sh
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the IAM create user and assume role demo."
  echo
  echo "This demo will create an IAM user, create an IAM role, and apply the role to the user."
  echo_repeat "*" 88
  echo

  echo -n "Enter a name for a new IAM user: "
  get_input
  user_name=$get_input_result

  local user_arn
  user_arn=$(iam_create_user -u "$user_name")

  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created demo IAM user named $user_name"
  else
    errecho "$user_arn"
    errecho "The user failed to create. This demo will exit."
    return 1
  fi

  local access_key_response
  access_key_response=$(iam_create_user_access_key -u "$user_name")
  # shellcheck disable=SC2181
  if [[ ${?} != 0 ]]; then
    errecho "The access key failed to create. This demo will exit."
    clean_up "$user_name"
    return 1
  fi

  IFS=$'\t ' read -r -a access_key_values <<<"$access_key_response"
  local key_name=${access_key_values[0]}
  local key_secret=${access_key_values[1]}

  echo "Created access key named $key_name"

  echo "Wait 10 seconds for the user to be ready."
  sleep 10
  echo_repeat "*" 88
  echo

  local iam_role_name
  iam_role_name=$(generate_random_name "test-role")
  echo "Creating a role named $iam_role_name with user $user_name as the principal."

  local assume_role_policy_document="{
    \"Version\": \"2012-10-17\",
    \"Statement\": [{
        \"Effect\": \"Allow\",
        \"Principal\": {\"AWS\": \"$user_arn\"},
        \"Action\": \"sts:AssumeRole\"
        }]
    }"

  local role_arn
  role_arn=$(iam_create_role -n "$iam_role_name" -p "$assume_role_policy_document")

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created IAM role named $iam_role_name"
  else
    errecho "The role failed to create. This demo will exit."
    clean_up "$user_name" "$key_name"
    return 1
  fi

  local policy_name
  policy_name=$(generate_random_name "test-policy")
  local policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]}"

  local policy_arn
  policy_arn=$(iam_create_policy -n "$policy_name" -p "$policy_document")
  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created  IAM policy named $policy_name"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name"
    return 1
  fi

  if (iam_attach_role_policy -n "$iam_role_name" -p "$policy_arn"); then
    echo "Attached policy $policy_arn to role $iam_role_name"
  else
    errecho "The policy failed to attach."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn"
    return 1
  fi

  local assume_role_policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"$role_arn\"}]}"

  local assume_role_policy_name
  assume_role_policy_name=$(generate_random_name "test-assume-role-")

  # shellcheck disable=SC2181
  local assume_role_policy_arn
  assume_role_policy_arn=$(iam_create_policy -n "$assume_role_policy_name" -p "$assume_role_policy_document")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created  IAM policy named $assume_role_policy_name for sts assume role"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn"
    return 1
  fi

  echo "Wait 10 seconds to give AWS time to propagate these new resources and connections."
  sleep 10
  echo_repeat "*" 88
  echo

  echo "Try to list buckets without the new user assuming the role."
  echo_repeat "*" 88
  echo

  # Set the environment variables for the created user.
  # bashsupport disable=BP2001
  export AWS_ACCESS_KEY_ID=$key_name
  # bashsupport disable=BP2001
  export AWS_SECRET_ACCESS_KEY=$key_secret

  local buckets
  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. This should not have happened."
  else
    errecho "Because the role with permissions has not been assumed, listing buckets failed."
  fi

  echo
  echo_repeat "*" 88
  echo "Now assume the role $iam_role_name and list the buckets."
  echo_repeat "*" 88
  echo

  local credentials

  credentials=$(sts_assume_role -r "$role_arn" -n "AssumeRoleDemoSession")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Assumed role $iam_role_name"
  else
    errecho "Failed to assume role."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  IFS=$'\t ' read -r -a credentials <<<"$credentials"

  export AWS_ACCESS_KEY_ID=${credentials[0]}
  export AWS_SECRET_ACCESS_KEY=${credentials[1]}
  # bashsupport disable=BP2001
  export AWS_SESSION_TOKEN=${credentials[2]}

  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. Listing buckets succeeded because of "
    echo "the assumed role."
  else
    errecho "Failed to list buckets. This should not happen."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    export AWS_SESSION_TOKEN=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  local result=0
  export AWS_ACCESS_KEY_ID=""
  export AWS_SECRET_ACCESS_KEY=""

  echo
  echo_repeat "*" 88
  echo "The created resources will now be deleted."
  echo_repeat "*" 88
  echo

  clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    result=1
  fi

  return $result
}
```
The IAM functions used in this scenario.  

```
###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}

###############################################################################
# function iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}

###############################################################################
# function iam_create_role
#
# This function creates an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_json -- The assume role policy document.
#
# Returns:
#       The ARN of the role.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_role() {
  local role_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_json -- The assume role policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-role \
    --role-name "$role_name" \
    --assume-role-policy-document "$policy_document" \
    --output text \
    --query Role.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-role operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+ For API details, see the following topics in *AWS CLI Command Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/PutUserPolicy)

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples). 

```
namespace AwsDoc {
    namespace IAM {
  
        //! Cleanup by deleting created entities.
        /*!
          \sa DeleteCreatedEntities
          \param client: IAM client.
          \param role: IAM role.
          \param user: IAM user.
          \param policy: IAM policy.
        */
        static bool DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                          const Aws::IAM::Model::Role &role,
                                          const Aws::IAM::Model::User &user,
                                          const Aws::IAM::Model::Policy &policy);
    }

    static const int LIST_BUCKETS_WAIT_SEC = 20;

    static const char ALLOCATION_TAG[] = "example_code";
}

//! Scenario to create an IAM user, create an IAM role, and apply the role to the user.
// "IAM access" permissions are needed to run this code.
// "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
//    create a custom policy).
/*!
  \sa iamCreateUserAssumeRoleScenario
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::iamCreateUserAssumeRoleScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::IAM::IAMClient client(clientConfig);
    Aws::IAM::Model::User user;
    Aws::IAM::Model::Role role;
    Aws::IAM::Model::Policy policy;

    // 1. Create a user.
    {
        Aws::IAM::Model::CreateUserRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String userName = "iam-demo-user-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetUserName(userName);

        Aws::IAM::Model::CreateUserOutcome outcome = client.CreateUser(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Error creating IAM user " << userName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            std::cout << "Successfully created IAM user " << userName << std::endl;
        }

        user = outcome.GetResult().GetUser();
    }

    // 2. Create a role.
    {
        // Get the IAM user for the current client in order to access its ARN.
        Aws::String iamUserArn;
        {
            Aws::IAM::Model::GetUserRequest request;
            Aws::IAM::Model::GetUserOutcome outcome = client.GetUser(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error getting Iam user. " <<
                          outcome.GetError().GetMessage() << std::endl;

                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }
            else {
                std::cout << "Successfully retrieved Iam user "
                          << outcome.GetResult().GetUser().GetUserName()
                          << std::endl;
            }

            iamUserArn = outcome.GetResult().GetUser().GetArn();
        }

        Aws::IAM::Model::CreateRoleRequest request;

        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleName = "iam-demo-role-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleName(roleName);

        // Build policy document for role.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");

        Aws::Utils::Document jsonPrincipal;
        jsonPrincipal.WithString("AWS", iamUserArn);
        jsonStatement.WithObject("Principal", jsonPrincipal);
        jsonStatement.WithString("Action", "sts:AssumeRole");
        jsonStatement.WithObject("Condition", Aws::Utils::Document());

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Setting policy for role\n   "
                  << policyDocument.View().WriteCompact() << std::endl;

        // Set role policy document as JSON string.
        request.SetAssumeRolePolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating role. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a role with name " << roleName
                      << std::endl;
        }

        role = outcome.GetResult().GetRole();
    }

    // 3. Create an IAM policy.
    {
        Aws::IAM::Model::CreatePolicyRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String policyName = "iam-demo-policy-" +
                                 Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetPolicyName(policyName);

        // Build IAM policy document.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");
        jsonStatement.WithString("Action", "s3:ListAllMyBuckets");
        jsonStatement.WithString("Resource", "arn:aws:s3:::*");

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Creating a policy.\n   " << policyDocument.View().WriteCompact()
                  << std::endl;

        // Set IAM policy document as JSON string.
        request.SetPolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreatePolicyOutcome outcome = client.CreatePolicy(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a policy with name, " << policyName <<
                      "." << std::endl;
        }

        policy = outcome.GetResult().GetPolicy();
    }

    // 4. Assume the new role using the AWS Security Token Service (STS).
    Aws::STS::Model::Credentials credentials;
    {
        Aws::STS::STSClient stsClient(clientConfig);

        Aws::STS::Model::AssumeRoleRequest request;
        request.SetRoleArn(role.GetArn());
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleSessionName = "iam-demo-role-session-" +
                                      Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleSessionName(roleSessionName);

        Aws::STS::Model::AssumeRoleOutcome assumeRoleOutcome;

        // Repeatedly call AssumeRole, because there is often a delay
        // before the role is available to be assumed.
        // Repeat at most 20 times when access is denied.
        int count = 0;
        while (true) {
            assumeRoleOutcome = stsClient.AssumeRole(request);
            if (!assumeRoleOutcome.IsSuccess()) {
                if (count > 20 ||
                    assumeRoleOutcome.GetError().GetErrorType() !=
                    Aws::STS::STSErrors::ACCESS_DENIED) {
                    std::cerr << "Error assuming role after 20 tries. " <<
                              assumeRoleOutcome.GetError().GetMessage() << std::endl;

                    DeleteCreatedEntities(client, role, user, policy);
                    return false;
                }
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                std::cout << "Successfully assumed the role after " << count
                          << " seconds." << std::endl;
                break;
            }
            count++;
        }

        credentials = assumeRoleOutcome.GetResult().GetCredentials();
    }


    // 5. List objects in the bucket (This should fail).
    {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if (listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
            }
            else {
                std::cout
                        << "Access to list buckets denied because privileges have not been applied."
                        << std::endl;
            }
        }
        else {
            std::cerr
                    << "Successfully retrieved bucket lists when this should not happen."
                    << std::endl;
        }
    }

    // 6. Attach the policy to the role.
    {
        Aws::IAM::Model::AttachRolePolicyRequest request;
        request.SetRoleName(role.GetRoleName());
        request.WithPolicyArn(policy.GetArn());

        Aws::IAM::Model::AttachRolePolicyOutcome outcome = client.AttachRolePolicy(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully attached the policy with name, "
                      << policy.GetPolicyName() <<
                      ", to the role, " << role.GetRoleName() << "." << std::endl;
        }
    }

    int count = 0;
    // 7. List objects in the bucket (this should succeed).
    // Repeatedly call ListBuckets, because there is often a delay
    // before the policy with ListBucket permissions has been applied to the role.
    // Repeat at most LIST_BUCKETS_WAIT_SEC times when access is denied.
    while (true) {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if ((count > LIST_BUCKETS_WAIT_SEC) ||
                listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets after " << LIST_BUCKETS_WAIT_SEC << " seconds. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        else {

            std::cout << "Successfully retrieved bucket lists after " << count
                      << " seconds." << std::endl;
            break;
        }
        count++;
    }

    // 8. Delete all the created resources.
    return DeleteCreatedEntities(client, role, user, policy);
}

bool AwsDoc::IAM::DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                        const Aws::IAM::Model::Role &role,
                                        const Aws::IAM::Model::User &user,
                                        const Aws::IAM::Model::Policy &policy) {
    bool result = true;
    if (policy.ArnHasBeenSet()) {
        // Detach the policy from the role.
        {
            Aws::IAM::Model::DetachRolePolicyRequest request;
            request.SetPolicyArn(policy.GetArn());
            request.SetRoleName(role.GetRoleName());

            Aws::IAM::Model::DetachRolePolicyOutcome outcome = client.DetachRolePolicy(
                    request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error Detaching policy from roles. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully detached the policy with arn "
                          << policy.GetArn()
                          << " from role " << role.GetRoleName() << "." << std::endl;
            }
        }

        // Delete the policy.
        {
            Aws::IAM::Model::DeletePolicyRequest request;
            request.WithPolicyArn(policy.GetArn());

            Aws::IAM::Model::DeletePolicyOutcome outcome = client.DeletePolicy(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error deleting policy. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully deleted the policy with arn "
                          << policy.GetArn() << std::endl;
            }
        }

    }

    if (role.RoleIdHasBeenSet()) {
        // Delete the role.
        Aws::IAM::Model::DeleteRoleRequest request;
        request.SetRoleName(role.GetRoleName());

        Aws::IAM::Model::DeleteRoleOutcome outcome = client.DeleteRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting role. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the role with name "
                      << role.GetRoleName() << std::endl;
        }
    }

    if (user.ArnHasBeenSet()) {
        // Delete the user.
        Aws::IAM::Model::DeleteUserRequest request;
        request.WithUserName(user.GetUserName());

        Aws::IAM::Model::DeleteUserOutcome outcome = client.DeleteUser(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting user. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the user with name "
                      << user.GetUserName() << std::endl;
        }
    }

    return result;
}
```
+ For API details, see the following topics in *AWS SDK for C\$1\$1 API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutUserPolicy)

------
#### [ Go ]

**SDK for Go V2**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples). 
Run an interactive scenario at a command prompt.  

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/sts"
	"github.com/aws/smithy-go"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/iam/actions"
)

// AssumeRoleScenario shows you how to use the AWS Identity and Access Management (IAM)
// service to perform the following actions:
//
//  1. Create a user who has no permissions.
//  2. Create a role that grants permission to list Amazon Simple Storage Service
//     (Amazon S3) buckets for the account.
//  3. Add a policy to let the user assume the role.
//  4. Try and fail to list buckets without permissions.
//  5. Assume the role and list S3 buckets using temporary credentials.
//  6. Delete the policy, role, and user.
type AssumeRoleScenario struct {
	sdkConfig      aws.Config
	accountWrapper actions.AccountWrapper
	policyWrapper  actions.PolicyWrapper
	roleWrapper    actions.RoleWrapper
	userWrapper    actions.UserWrapper
	questioner     demotools.IQuestioner
	helper         IScenarioHelper
	isTestRun      bool
}

// NewAssumeRoleScenario constructs an AssumeRoleScenario instance from a configuration.
// It uses the specified config to get an IAM client and create wrappers for the actions
// used in the scenario.
func NewAssumeRoleScenario(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) AssumeRoleScenario {
	iamClient := iam.NewFromConfig(sdkConfig)
	return AssumeRoleScenario{
		sdkConfig:      sdkConfig,
		accountWrapper: actions.AccountWrapper{IamClient: iamClient},
		policyWrapper:  actions.PolicyWrapper{IamClient: iamClient},
		roleWrapper:    actions.RoleWrapper{IamClient: iamClient},
		userWrapper:    actions.UserWrapper{IamClient: iamClient},
		questioner:     questioner,
		helper:         helper,
	}
}

// addTestOptions appends the API options specified in the original configuration to
// another configuration. This is used to attach the middleware stubber to clients
// that are constructed during the scenario, which is needed for unit testing.
func (scenario AssumeRoleScenario) addTestOptions(scenarioConfig *aws.Config) {
	if scenario.isTestRun {
		scenarioConfig.APIOptions = append(scenarioConfig.APIOptions, scenario.sdkConfig.APIOptions...)
	}
}

// Run runs the interactive scenario.
func (scenario AssumeRoleScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo.\n")
			log.Println(r)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the AWS Identity and Access Management (IAM) assume role demo.")
	log.Println(strings.Repeat("-", 88))

	user := scenario.CreateUser(ctx)
	accessKey := scenario.CreateAccessKey(ctx, user)
	role := scenario.CreateRoleAndPolicies(ctx, user)
	noPermsConfig := scenario.ListBucketsWithoutPermissions(ctx, accessKey)
	scenario.ListBucketsWithAssumedRole(ctx, noPermsConfig, role)
	scenario.Cleanup(ctx, user, role)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateUser creates a new IAM user. This user has no permissions.
func (scenario AssumeRoleScenario) CreateUser(ctx context.Context) *types.User {
	log.Println("Let's create an example user with no permissions.")
	userName := scenario.questioner.Ask("Enter a name for the example user:", demotools.NotEmpty{})
	user, err := scenario.userWrapper.GetUser(ctx, userName)
	if err != nil {
		panic(err)
	}
	if user == nil {
		user, err = scenario.userWrapper.CreateUser(ctx, userName)
		if err != nil {
			panic(err)
		}
		log.Printf("Created user %v.\n", *user.UserName)
	} else {
		log.Printf("User %v already exists.\n", *user.UserName)
	}
	log.Println(strings.Repeat("-", 88))
	return user
}

// CreateAccessKey creates an access key for the user.
func (scenario AssumeRoleScenario) CreateAccessKey(ctx context.Context, user *types.User) *types.AccessKey {
	accessKey, err := scenario.userWrapper.CreateAccessKeyPair(ctx, *user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("Created access key %v for your user.", *accessKey.AccessKeyId)
	log.Println("Waiting a few seconds for your user to be ready...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return accessKey
}

// CreateRoleAndPolicies creates a policy that grants permission to list S3 buckets for
// the current account and attaches the policy to a newly created role. It also adds an
// inline policy to the specified user that grants the user permission to assume the role.
func (scenario AssumeRoleScenario) CreateRoleAndPolicies(ctx context.Context, user *types.User) *types.Role {
	log.Println("Let's create a role and policy that grant permission to list S3 buckets.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	listBucketsRole, err := scenario.roleWrapper.CreateRole(ctx, scenario.helper.GetName(), *user.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created role %v.\n", *listBucketsRole.RoleName)
	listBucketsPolicy, err := scenario.policyWrapper.CreatePolicy(
		ctx, scenario.helper.GetName(), []string{"s3:ListAllMyBuckets"}, "arn:aws:s3:::*")
	if err != nil {
		panic(err)
	}
	log.Printf("Created policy %v.\n", *listBucketsPolicy.PolicyName)
	err = scenario.roleWrapper.AttachRolePolicy(ctx, *listBucketsPolicy.Arn, *listBucketsRole.RoleName)
	if err != nil {
		panic(err)
	}
	log.Printf("Attached policy %v to role %v.\n", *listBucketsPolicy.PolicyName,
		*listBucketsRole.RoleName)
	err = scenario.userWrapper.CreateUserPolicy(ctx, *user.UserName, scenario.helper.GetName(),
		[]string{"sts:AssumeRole"}, *listBucketsRole.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created an inline policy for user %v that lets the user assume the role.\n",
		*user.UserName)
	log.Println("Let's give AWS a few seconds to propagate these new resources and connections...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return listBucketsRole
}

// ListBucketsWithoutPermissions creates an Amazon S3 client from the user's access key
// credentials and tries to list buckets for the account. Because the user does not have
// permission to perform this action, the action fails.
func (scenario AssumeRoleScenario) ListBucketsWithoutPermissions(ctx context.Context, accessKey *types.AccessKey) *aws.Config {
	log.Println("Let's try to list buckets without permissions. This should return an AccessDenied error.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	noPermsConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*accessKey.AccessKeyId, *accessKey.SecretAccessKey, ""),
		))
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&noPermsConfig)

	s3Client := s3.NewFromConfig(noPermsConfig)
	_, err = s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		// The SDK for Go does not model the AccessDenied error, so check ErrorCode directly.
		var ae smithy.APIError
		if errors.As(err, &ae) {
			switch ae.ErrorCode() {
			case "AccessDenied":
				log.Println("Got AccessDenied error, which is the expected result because\n" +
					"the ListBuckets call was made without permissions.")
			default:
				log.Println("Expected AccessDenied, got something else.")
				panic(err)
			}
		}
	} else {
		log.Println("Expected AccessDenied error when calling ListBuckets without permissions,\n" +
			"but the call succeeded. Continuing the example anyway...")
	}
	log.Println(strings.Repeat("-", 88))
	return &noPermsConfig
}

// ListBucketsWithAssumedRole performs the following actions:
//
//  1. Creates an AWS Security Token Service (AWS STS) client from the config created from
//     the user's access key credentials.
//  2. Gets temporary credentials by assuming the role that grants permission to list the
//     buckets.
//  3. Creates an Amazon S3 client from the temporary credentials.
//  4. Lists buckets for the account. Because the temporary credentials are generated by
//     assuming the role that grants permission, the action succeeds.
func (scenario AssumeRoleScenario) ListBucketsWithAssumedRole(ctx context.Context, noPermsConfig *aws.Config, role *types.Role) {
	log.Println("Let's assume the role that grants permission to list buckets and try again.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	stsClient := sts.NewFromConfig(*noPermsConfig)
	tempCredentials, err := stsClient.AssumeRole(ctx, &sts.AssumeRoleInput{
		RoleArn:         role.Arn,
		RoleSessionName: aws.String("AssumeRoleExampleSession"),
		DurationSeconds: aws.Int32(900),
	})
	if err != nil {
		log.Printf("Couldn't assume role %v.\n", *role.RoleName)
		panic(err)
	}
	log.Printf("Assumed role %v, got temporary credentials.\n", *role.RoleName)
	assumeRoleConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*tempCredentials.Credentials.AccessKeyId,
			*tempCredentials.Credentials.SecretAccessKey,
			*tempCredentials.Credentials.SessionToken),
		),
	)
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&assumeRoleConfig)

	s3Client := s3.NewFromConfig(assumeRoleConfig)
	result, err := s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		log.Println("Couldn't list buckets with assumed role credentials.")
		panic(err)
	}
	log.Println("Successfully called ListBuckets with assumed role credentials, \n" +
		"here are some of them:")
	for i := 0; i < len(result.Buckets) && i < 5; i++ {
		log.Printf("\t%v\n", *result.Buckets[i].Name)
	}
	log.Println(strings.Repeat("-", 88))
}

// Cleanup deletes all resources created for the scenario.
func (scenario AssumeRoleScenario) Cleanup(ctx context.Context, user *types.User, role *types.Role) {
	if scenario.questioner.AskBool(
		"Do you want to delete the resources created for this example? (y/n)", "y",
	) {
		policies, err := scenario.roleWrapper.ListAttachedRolePolicies(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		for _, policy := range policies {
			err = scenario.roleWrapper.DetachRolePolicy(ctx, *role.RoleName, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			err = scenario.policyWrapper.DeletePolicy(ctx, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			log.Printf("Detached policy %v from role %v and deleted the policy.\n",
				*policy.PolicyName, *role.RoleName)
		}
		err = scenario.roleWrapper.DeleteRole(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted role %v.\n", *role.RoleName)

		userPols, err := scenario.userWrapper.ListUserPolicies(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, userPol := range userPols {
			err = scenario.userWrapper.DeleteUserPolicy(ctx, *user.UserName, userPol)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted policy %v from user %v.\n", userPol, *user.UserName)
		}
		keys, err := scenario.userWrapper.ListAccessKeys(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, key := range keys {
			err = scenario.userWrapper.DeleteAccessKey(ctx, *user.UserName, *key.AccessKeyId)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted access key %v from user %v.\n", *key.AccessKeyId, *user.UserName)
		}
		err = scenario.userWrapper.DeleteUser(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted user %v.\n", *user.UserName)
		log.Println(strings.Repeat("-", 88))
	}

}

// IScenarioHelper abstracts input and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	GetName() string
	Pause(secs int)
}

const rMax = 100000

type ScenarioHelper struct {
	Prefix string
	Random *rand.Rand
}

// GetName returns a unique name formed of a prefix and a random number.
func (helper *ScenarioHelper) GetName() string {
	return fmt.Sprintf("%v%v", helper.Prefix, helper.Random.Intn(rMax))
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}
```
Define a struct that wraps account actions.  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
Define a struct that wraps policy actions.  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
Define a struct that wraps role actions.  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}



// CreateRole creates a role that trusts a specified user. The trusted user can assume
// the role to acquire its permissions.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper RoleWrapper) CreateRole(ctx context.Context, roleName string, trustedUserArn string) (*types.Role, error) {
	var role *types.Role
	trustPolicy := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Principal: map[string]string{"AWS": trustedUserArn},
			Action:    []string{"sts:AssumeRole"},
		}},
	}
	policyBytes, err := json.Marshal(trustPolicy)
	if err != nil {
		log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreateRole(ctx, &iam.CreateRoleInput{
		AssumeRolePolicyDocument: aws.String(string(policyBytes)),
		RoleName:                 aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
Define a struct that wraps user actions.  

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+ For API details, see the following topics in *AWS SDK for Go API Reference*.
  + [AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)
  + [CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)
  + [CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)
  + [CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)
  + [CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)
  + [DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)
  + [DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)
  + [DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)
  + [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)
  + [DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)
  + [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)

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

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples). 
Create functions that wrap IAM user actions.  

```
/*
  To run this Java V2 code example, set up your development environment, including your credentials.

  For information, see this documentation topic:

  https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html

  This example performs these operations:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role.  Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.
 */

public class IAMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"s3:*\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static String userArn;

    public static void main(String[] args) throws Exception {

        final String usage = """

                Usage:
                    <username> <policyName> <roleName> <roleSessionName> <bucketName>\s

                Where:
                    username - The name of the IAM user to create.\s
                    policyName - The name of the policy to create.\s
                    roleName - The name of the role to create.\s
                    roleSessionName - The name of the session required for the assumeRole operation.\s
                    bucketName - The name of the Amazon S3 bucket from which objects are read.\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String userName = args[0];
        String policyName = args[1];
        String roleName = args[2];
        String roleSessionName = args[3];
        String bucketName = args[4];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS IAM example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 1. Create the IAM user.");
        User createUser = createIAMUser(iam, userName);

        System.out.println(DASHES);
        userArn = createUser.arn();

        AccessKey myKey = createIAMAccessKey(iam, userName);
        String accessKey = myKey.accessKeyId();
        String secretKey = myKey.secretAccessKey();
        String assumeRolePolicyDocument = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "	\"AWS\": \"" + userArn + "\"" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        System.out.println(assumeRolePolicyDocument);
        System.out.println(userName + " was successfully created.");
        System.out.println(DASHES);
        System.out.println("2. Creates a policy.");
        String polArn = createIAMPolicy(iam, policyName);
        System.out.println("The policy " + polArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Creates a role.");
        TimeUnit.SECONDS.sleep(30);
        String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument);
        System.out.println(roleArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Grants the user permissions.");
        attachIAMRolePolicy(iam, roleName, polArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Wait for 30 secs so the resource is available");
        TimeUnit.SECONDS.sleep(30);
        System.out.println("5. Gets temporary credentials by assuming the role.");
        System.out.println("Perform an Amazon S3 Service operation using the temporary credentials.");
        assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6 Getting ready to delete the AWS resources");
        deleteKey(iam, userName, accessKey);
        deleteRole(iam, roleName, polArn);
        deleteIAMUser(iam, userName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("This IAM Scenario has successfully completed");
        System.out.println(DASHES);
    }

    public static AccessKey createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static User createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object
            IamWaiter iamWaiter = iam.waiter();
            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            // Wait until the user is created.
            CreateUserResponse response = iam.createUser(request);
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static String createIAMRole(IamClient iam, String rolename, String json) {

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(json)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse response = iam.createRole(request);
            System.out.println("The ARN of the role is " + response.role().arn());
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();
            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument).build();

            CreatePolicyResponse response = iam.createPolicy(request);
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
            String polArn;
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);
            System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Invoke an Amazon S3 operation using the Assumed Role.
    public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal,
            String keySecret) {

        // Use the creds of the new IAM user that was created in this code example.
        AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret);
        StsClient stsClient = StsClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .build();

        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();
            String key = myCreds.accessKeyId();
            String secKey = myCreds.secretAccessKey();
            String secToken = myCreds.sessionToken();

            // List all objects in an Amazon S3 bucket using the temp creds retrieved by
            // invoking assumeRole.
            Region region = Region.US_EAST_1;
            S3Client s3 = S3Client.builder()
                    .credentialsProvider(
                            StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken)))
                    .region(region)
                    .build();

            System.out.println("Created a S3Client using temp credentials.");
            System.out.println("Listing objects in " + bucketName);
            ListObjectsRequest listObjects = ListObjectsRequest.builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();
            for (S3Object myValue : objects) {
                System.out.println("The name of the key is " + myValue.key());
                System.out.println("The owner is " + myValue.owner());
            }

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteRole(IamClient iam, String roleName, String polArn) {

        try {
            // First the policy needs to be detached.
            DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                    .policyArn(polArn)
                    .roleName(roleName)
                    .build();

            iam.detachRolePolicy(rolePolicyRequest);

            // Delete the policy.
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(polArn)
                    .build();

            iam.deletePolicy(request);
            System.out.println("*** Successfully deleted " + polArn);

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("*** Successfully deleted " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ For API details, see the following topics in *AWS SDK for Java 2.x API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/PutUserPolicy)

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

**SDK for JavaScript (v3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples). 
Create an IAM user and a role that grants permission to list Amazon S3 buckets. The user has rights only to assume the role. After assuming the role, use temporary credentials to list buckets for the account.  

```
import {
  CreateUserCommand,
  GetUserCommand,
  CreateAccessKeyCommand,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  DeleteAccessKeyCommand,
  DeleteUserCommand,
  DeleteRoleCommand,
  DeletePolicyCommand,
  DetachRolePolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";
import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario/index.js";

// Set the parameters.
const iamClient = new IAMClient({});
const userName = "iam_basic_test_username";
const policyName = "iam_basic_test_policy";
const roleName = "iam_basic_test_role";

/**
 * Create a new IAM user. If the user already exists, give
 * the option to delete and re-create it.
 * @param {string} name
 */
export const createUser = async (name, confirmAll = false) => {
  try {
    const { User } = await iamClient.send(
      new GetUserCommand({ UserName: name }),
    );
    const input = new ScenarioInput(
      "deleteUser",
      "Do you want to delete and remake this user?",
      { type: "confirm" },
    );
    const deleteUser = await input.handle({}, { confirmAll });
    // If the user exists, and you want to delete it, delete the user
    // and then create it again.
    if (deleteUser) {
      await iamClient.send(new DeleteUserCommand({ UserName: User.UserName }));
      await iamClient.send(new CreateUserCommand({ UserName: name }));
    } else {
      console.warn(
        `${name} already exists. The scenario may not work as expected.`,
      );
      return User;
    }
  } catch (caught) {
    // If there is no user by that name, create one.
    if (caught instanceof Error && caught.name === "NoSuchEntityException") {
      const { User } = await iamClient.send(
        new CreateUserCommand({ UserName: name }),
      );
      return User;
    }
    throw caught;
  }
};

export const main = async (confirmAll = false) => {
  // Create a user. The user has no permissions by default.
  const User = await createUser(userName, confirmAll);

  if (!User) {
    throw new Error("User not created");
  }

  // Create an access key. This key is used to authenticate the new user to
  // Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS).
  // It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/.
  const createAccessKeyResponse = await iamClient.send(
    new CreateAccessKeyCommand({ UserName: userName }),
  );

  if (
    !createAccessKeyResponse.AccessKey?.AccessKeyId ||
    !createAccessKeyResponse.AccessKey?.SecretAccessKey
  ) {
    throw new Error("Access key not created");
  }

  const {
    AccessKey: { AccessKeyId, SecretAccessKey },
  } = createAccessKeyResponse;

  let s3Client = new S3Client({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the list buckets operation until it succeeds. InvalidAccessKeyId is
  // thrown while the user and access keys are still stabilizing.
  await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => {
    try {
      return await listBuckets(s3Client);
    } catch (err) {
      if (err instanceof Error && err.name === "InvalidAccessKeyId") {
        throw err;
      }
    }
  });

  // Retry the create role operation until it succeeds. A MalformedPolicyDocument error
  // is thrown while the user and access keys are still stabilizing.
  const { Role } = await retry(
    {
      intervalInMs: 2000,
      maxRetries: 60,
    },
    () =>
      iamClient.send(
        new CreateRoleCommand({
          AssumeRolePolicyDocument: JSON.stringify({
            Version: "2012-10-17",
            Statement: [
              {
                Effect: "Allow",
                Principal: {
                  // Allow the previously created user to assume this role.
                  AWS: User.Arn,
                },
                Action: "sts:AssumeRole",
              },
            ],
          }),
          RoleName: roleName,
        }),
      ),
  );

  if (!Role) {
    throw new Error("Role not created");
  }

  // Create a policy that allows the user to list S3 buckets.
  const { Policy: listBucketPolicy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Action: ["s3:ListAllMyBuckets"],
            Resource: "*",
          },
        ],
      }),
      PolicyName: policyName,
    }),
  );

  if (!listBucketPolicy) {
    throw new Error("Policy not created");
  }

  // Attach the policy granting the 's3:ListAllMyBuckets' action to the role.
  await iamClient.send(
    new AttachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  // Assume the role.
  const stsClient = new STSClient({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the assume role operation until it succeeds.
  const { Credentials } = await retry(
    { intervalInMs: 2000, maxRetries: 60 },
    () =>
      stsClient.send(
        new AssumeRoleCommand({
          RoleArn: Role.Arn,
          RoleSessionName: `iamBasicScenarioSession-${Math.floor(
            Math.random() * 1000000,
          )}`,
          DurationSeconds: 900,
        }),
      ),
  );

  if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) {
    throw new Error("Credentials not created");
  }

  s3Client = new S3Client({
    credentials: {
      accessKeyId: Credentials.AccessKeyId,
      secretAccessKey: Credentials.SecretAccessKey,
      sessionToken: Credentials.SessionToken,
    },
  });

  // List the S3 buckets again.
  // Retry the list buckets operation until it succeeds. AccessDenied might
  // be thrown while the role policy is still stabilizing.
  await retry({ intervalInMs: 2000, maxRetries: 120 }, () =>
    listBuckets(s3Client),
  );

  // Clean up.
  await iamClient.send(
    new DetachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeletePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
    }),
  );

  await iamClient.send(
    new DeleteRoleCommand({
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeleteAccessKeyCommand({
      UserName: userName,
      AccessKeyId,
    }),
  );

  await iamClient.send(
    new DeleteUserCommand({
      UserName: userName,
    }),
  );
};

/**
 *
 * @param {S3Client} s3Client
 */
const listBuckets = async (s3Client) => {
  const { Buckets } = await s3Client.send(new ListBucketsCommand({}));

  if (!Buckets) {
    throw new Error("Buckets not listed");
  }

  console.log(Buckets.map((bucket) => bucket.Name).join("\n"));
};
```
+ For API details, see the following topics in *AWS SDK for JavaScript API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)
  + [CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)
  + [CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)
  + [CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)
  + [CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)
  + [DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)
  + [DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)
  + [DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserPolicyCommand)
  + [DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)
  + [PutUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutUserPolicyCommand)

------
#### [ Kotlin ]

**SDK for Kotlin**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples). 
Create functions that wrap IAM user actions.  

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> 

    Where:
        username - The name of the IAM user to create. 
        policyName - The name of the policy to create. 
        roleName - The name of the role to create. 
        roleSessionName - The name of the session required for the assumeRole operation. 
        fileLocation - The file location to the JSON required to create the role (see Readme). 
        bucketName - The name of the Amazon S3 bucket from which objects are read. 
    """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val userName = args[0]
    val policyName = args[1]
    val roleName = args[2]
    val roleSessionName = args[3]
    val fileLocation = args[4]
    val bucketName = args[5]

    createUser(userName)
    println("$userName was successfully created.")

    val polArn = createPolicy(policyName)
    println("The policy $polArn was successfully created.")

    val roleArn = createRole(roleName, fileLocation)
    println("$roleArn was successfully created.")
    attachRolePolicy(roleName, polArn)

    println("*** Wait for 1 MIN so the resource is available.")
    delay(60000)
    assumeGivenRole(roleArn, roleSessionName, bucketName)

    println("*** Getting ready to delete the AWS resources.")
    deleteRole(roleName, polArn)
    deleteUser(userName)
    println("This IAM Scenario has successfully completed.")
}

suspend fun createUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}

suspend fun createPolicy(policyNameVal: String?): String {
    val policyDocumentValue = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:*"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentValue
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}

suspend fun createRole(
    rolenameVal: String?,
    fileLocation: String?,
): String? {
    val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject

    val request =
        CreateRoleRequest {
            roleName = rolenameVal
            assumeRolePolicyDocument = jsonObject.toJSONString()
            description = "Created using the AWS SDK for Kotlin"
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createRole(request)
        return response.role?.arn
    }
}

suspend fun attachRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkMyList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkMyList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}

suspend fun assumeGivenRole(
    roleArnVal: String?,
    roleSessionNameVal: String?,
    bucketName: String,
) {
    val stsClient = StsClient.fromEnvironment { region = "us-east-1" }
    val roleRequest =
        AssumeRoleRequest {
            roleArn = roleArnVal
            roleSessionName = roleSessionNameVal
        }

    val roleResponse = stsClient.assumeRole(roleRequest)
    val myCreds = roleResponse.credentials
    val key = myCreds?.accessKeyId
    val secKey = myCreds?.secretAccessKey
    val secToken = myCreds?.sessionToken

    val staticCredentials = StaticCredentialsProvider {
        accessKeyId = key
        secretAccessKey = secKey
        sessionToken = secToken
    }

    // List all objects in an Amazon S3 bucket using the temp creds.
    val s3 = S3Client.fromEnvironment {
        region = "us-east-1"
        credentialsProvider = staticCredentials
    }

    println("Created a S3Client using temp credentials.")
    println("Listing objects in $bucketName")

    val listObjects =
        ListObjectsRequest {
            bucket = bucketName
        }

    val response = s3.listObjects(listObjects)
    response.contents?.forEach { myObject ->
        println("The name of the key is ${myObject.key}")
        println("The owner is ${myObject.owner}")
    }
}

suspend fun deleteRole(
    roleNameVal: String,
    polArn: String,
) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }

    // First the policy needs to be detached.
    val rolePolicyRequest =
        DetachRolePolicyRequest {
            policyArn = polArn
            roleName = roleNameVal
        }

    iam.detachRolePolicy(rolePolicyRequest)

    // Delete the policy.
    val request =
        DeletePolicyRequest {
            policyArn = polArn
        }

    iam.deletePolicy(request)
    println("*** Successfully deleted $polArn")

    // Delete the role.
    val roleRequest =
        DeleteRoleRequest {
            roleName = roleNameVal
        }

    iam.deleteRole(roleRequest)
    println("*** Successfully deleted $roleNameVal")
}

suspend fun deleteUser(userNameVal: String) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    iam.deleteUser(request)
    println("*** Successfully deleted $userNameVal")
}

@Throws(java.lang.Exception::class)
fun readJsonSimpleDemo(filename: String): Any? {
    val reader = FileReader(filename)
    val jsonParser = JSONParser()
    return jsonParser.parse(reader)
}
```
+ For API details, see the following topics in *AWS SDK for Kotlin API reference*.
  + [AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

------
#### [ PHP ]

**SDK for PHP**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples). 

```
namespace Iam\Basics;

require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;
use Iam\IAMService;

echo("\n");
echo("--------------------------------------\n");
print("Welcome to the IAM getting started demo using PHP!\n");
echo("--------------------------------------\n");

$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";

$key = $service->createAccessKey($user['UserName']);
$assumeRolePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{$user['Arn']}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }";
$assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument);
echo "Created role: {$assumeRoleRole['RoleName']}\n";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

$inlinePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{$assumeRoleRole['Arn']}\"}]
}";
$inlinePolicy = $service->createUserPolicy("iam_demo_inline_policy_$uuid", $inlinePolicyDocument, $user['UserName']);
//First, fail to list the buckets with the user
$credentials = new Credentials($key['AccessKeyId'], $key['SecretAccessKey']);
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
try {
    $s3Client->listBuckets([
    ]);
    echo "this should not run";
} catch (S3Exception $exception) {
    echo "successfully failed!\n";
}

$stsClient = new StsClient(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
sleep(10);
$assumedRole = $stsClient->assumeRole([
    'RoleArn' => $assumeRoleRole['Arn'],
    'RoleSessionName' => "DemoAssumeRoleSession_$uuid",
]);
$assumedCredentials = [
    'key' => $assumedRole['Credentials']['AccessKeyId'],
    'secret' => $assumedRole['Credentials']['SecretAccessKey'],
    'token' => $assumedRole['Credentials']['SessionToken'],
];
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $assumedCredentials]);
try {
    $s3Client->listBuckets([]);
    echo "this should now run!\n";
} catch (S3Exception $exception) {
    echo "this should now not fail\n";
}

$service->detachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);
$deletePolicy = $service->deletePolicy($listAllBucketsPolicy['Arn']);
echo "Delete policy: {$listAllBucketsPolicy['PolicyName']}\n";
$deletedRole = $service->deleteRole($assumeRoleRole['Arn']);
echo "Deleted role: {$assumeRoleRole['RoleName']}\n";
$deletedKey = $service->deleteAccessKey($key['AccessKeyId'], $user['UserName']);
$deletedUser = $service->deleteUser($user['UserName']);
echo "Delete user: {$user['UserName']}\n";
```
+ For API details, see the following topics in *AWS SDK for PHP API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Python ]

**SDK for Python (Boto3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples). 
Create an IAM user and a role that grants permission to list Amazon S3 buckets. The user has rights only to assume the role. After assuming the role, use temporary credentials to list buckets for the account.  

```
import json
import sys
import time
from uuid import uuid4

import boto3
from botocore.exceptions import ClientError


def progress_bar(seconds):
    """Shows a simple progress bar in the command window."""
    for _ in range(seconds):
        time.sleep(1)
        print(".", end="")
        sys.stdout.flush()
    print()


def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role.
    Creates a policy that allows listing Amazon S3 buckets.
    Attaches the policy to the role.
    Creates an inline policy for the user that lets the user assume the role.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, roles, and policies
                         in the account.
    :return: The newly created user, user key, and role.
    """
    try:
        user = iam_resource.create_user(UserName=f"demo-user-{uuid4()}")
        print(f"Created user {user.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a user for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user_key = user.create_access_key_pair()
        print(f"Created access key pair for user.")
    except ClientError as error:
        print(
            f"Couldn't create access keys for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    try:
        role = iam_resource.create_role(
            RoleName=f"demo-role-{uuid4()}",
            AssumeRolePolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": user.arn},
                            "Action": "sts:AssumeRole",
                        }
                    ],
                }
            ),
        )
        print(f"Created role {role.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a role for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        policy = iam_resource.create_policy(
            PolicyName=f"demo-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "s3:ListAllMyBuckets",
                            "Resource": "arn:aws:s3:::*",
                        }
                    ],
                }
            ),
        )
        role.attach_policy(PolicyArn=policy.arn)
        print(f"Created policy {policy.policy_name} and attached it to the role.")
    except ClientError as error:
        print(
            f"Couldn't create a policy and attach it to role {role.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user.create_policy(
            PolicyName=f"demo-user-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "sts:AssumeRole",
                            "Resource": role.arn,
                        }
                    ],
                }
            ),
        )
        print(
            f"Created an inline policy for {user.name} that lets the user assume "
            f"the role."
        )
    except ClientError as error:
        print(
            f"Couldn't create an inline policy for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, role


def show_access_denied_without_role(user_key):
    """
    Shows that listing buckets without first assuming the role is not allowed.

    :param user_key: The key of the user created during setup. This user does not
                     have permission to list buckets in the account.
    """
    print(f"Try to list buckets without first assuming the role.")
    s3_denied_resource = boto3.resource(
        "s3", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        for bucket in s3_denied_resource.buckets.all():
            print(bucket.name)
        raise RuntimeError("Expected to get AccessDenied error when listing buckets!")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Attempt to list buckets with no permissions: AccessDenied.")
        else:
            raise


def list_buckets_from_assumed_role(user_key, assume_role_arn, session_name):
    """
    Assumes a role that grants permission to list the Amazon S3 buckets in the account.
    Uses the temporary credentials from the role to list the buckets that are owned
    by the assumed role's account.

    :param user_key: The access key of a user that has permission to assume the role.
    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    """
    sts_client = boto3.client(
        "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        response = sts_client.assume_role(
            RoleArn=assume_role_arn, RoleSessionName=session_name
        )
        temp_credentials = response["Credentials"]
        print(f"Assumed role {assume_role_arn} and got temporary credentials.")
    except ClientError as error:
        print(
            f"Couldn't assume role {assume_role_arn}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    # Create an S3 resource that can access the account with the temporary credentials.
    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )
    print(f"Listing buckets for the assumed role's account:")
    try:
        for bucket in s3_resource.buckets.all():
            print(bucket.name)
    except ClientError as error:
        print(
            f"Couldn't list buckets for the account. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise




def teardown(user, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    try:
        for attached in role.attached_policies.all():
            policy_name = attached.policy_name
            role.detach_policy(PolicyArn=attached.arn)
            attached.delete()
            print(f"Detached and deleted {policy_name}.")
        role.delete()
        print(f"Deleted {role.name}.")
    except ClientError as error:
        print(
            "Couldn't detach policy, delete policy, or delete role. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        for user_pol in user.policies.all():
            user_pol.delete()
            print("Deleted inline user policy.")
        for key in user.access_keys.all():
            key.delete()
            print("Deleted user's access key.")
        user.delete()
        print(f"Deleted {user.name}.")
    except ClientError as error:
        print(
            "Couldn't delete user policy or delete user. Here's why: "
            f"{error.response['Error']['Message']}"
        )


def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the IAM create user and assume role demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user = None
    role = None
    try:
        user, user_key, role = setup(iam_resource)
        print(f"Created {user.name} and {role.name}.")
        show_access_denied_without_role(user_key)
        list_buckets_from_assumed_role(user_key, role.arn, "AssumeRoleDemoSession")
    except Exception:
        print("Something went wrong!")
    finally:
        if user is not None and role is not None:
            teardown(user, role)
        print("Thanks for watching!")


if __name__ == "__main__":
    usage_demo()
```
+ For API details, see the following topics in *AWS SDK for Python (Boto3) API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/PutUserPolicy)

------
#### [ Ruby ]

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples). 
Create an IAM user and a role that grants permission to list Amazon S3 buckets. The user has rights only to assume the role. After assuming the role, use temporary credentials to list buckets for the account.  

```
# Wraps the scenario actions.
class ScenarioCreateUserAssumeRole
  attr_reader :iam_client

  # @param [Aws::IAM::Client] iam_client: The AWS IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Waits for the specified number of seconds.
  #
  # @param duration [Integer] The number of seconds to wait.
  def wait(duration)
    puts('Give AWS time to propagate resources...')
    sleep(duration)
  end

  # Creates a user.
  #
  # @param user_name [String] The name to give the user.
  # @return [Aws::IAM::User] The newly created user.
  def create_user(user_name)
    user = @iam_client.create_user(user_name: user_name).user
    @logger.info("Created demo user named #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info('Tried and failed to create demo user.')
    @logger.info("\t#{e.code}: #{e.message}")
    @logger.info("\nCan't continue the demo without a user!")
    raise
  else
    user
  end

  # Creates an access key for a user.
  #
  # @param user [Aws::IAM::User] The user that owns the key.
  # @return [Aws::IAM::AccessKeyPair] The newly created access key.
  def create_access_key_pair(user)
    user_key = @iam_client.create_access_key(user_name: user.user_name).access_key
    @logger.info("Created accesskey pair for user #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create access keys for user #{user.user_name}.")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    user_key
  end

  # Creates a role that can be assumed by a user.
  #
  # @param role_name [String] The name to give the role.
  # @param user [Aws::IAM::User] The user who is granted permission to assume the role.
  # @return [Aws::IAM::Role] The newly created role.
  def create_role(role_name, user)
    trust_policy = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Principal: { 'AWS': user.arn },
        Action: 'sts:AssumeRole'
      }]
    }.to_json
    role = @iam_client.create_role(
      role_name: role_name,
      assume_role_policy_document: trust_policy
    ).role
    @logger.info("Created role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a role for the demo. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end

  # Creates a policy that grants permission to list S3 buckets in the account, and
  # then attaches the policy to a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param role [Aws::IAM::Role] The role that the policy is attached to.
  # @return [Aws::IAM::Policy] The newly created policy.
  def create_and_attach_role_policy(policy_name, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 's3:ListAllMyBuckets',
        Resource: 'arn:aws:s3:::*'
      }]
    }.to_json
    policy = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document
    ).policy
    @iam_client.attach_role_policy(
      role_name: role.role_name,
      policy_arn: policy.arn
    )
    @logger.info("Created policy #{policy.policy_name} and attached it to role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a policy and attach it to role #{role.role_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an inline policy for a user that lets the user assume a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param user [Aws::IAM::User] The user that owns the policy.
  # @param role [Aws::IAM::Role] The role that can be assumed.
  # @return [Aws::IAM::UserPolicy] The newly created policy.
  def create_user_policy(policy_name, user, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 'sts:AssumeRole',
        Resource: role.arn
      }]
    }.to_json
    @iam_client.put_user_policy(
      user_name: user.user_name,
      policy_name: policy_name,
      policy_document: policy_document
    )
    puts("Created an inline policy for #{user.user_name} that lets the user assume role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create an inline policy for user #{user.user_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an Amazon S3 resource with specified credentials. This is separated into a
  # factory function so that it can be mocked for unit testing.
  #
  # @param credentials [Aws::Credentials] The credentials used by the Amazon S3 resource.
  def create_s3_resource(credentials)
    Aws::S3::Resource.new(client: Aws::S3::Client.new(credentials: credentials))
  end

  # Lists the S3 buckets for the account, using the specified Amazon S3 resource.
  # Because the resource uses credentials with limited access, it may not be able to
  # list the S3 buckets.
  #
  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def list_buckets(s3_resource)
    count = 10
    s3_resource.buckets.each do |bucket|
      @logger.info "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
  rescue Aws::Errors::ServiceError => e
    if e.code == 'AccessDenied'
      puts('Attempt to list buckets with no permissions: AccessDenied.')
    else
      @logger.info("Couldn't list buckets for the account. Here's why: ")
      @logger.info("\t#{e.code}: #{e.message}")
      raise
    end
  end

  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end

  # Deletes a role. If the role has policies attached, they are detached and
  # deleted before the role is deleted.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    @iam_client.list_attached_role_policies(role_name: role_name).attached_policies.each do |policy|
      @iam_client.detach_role_policy(role_name: role_name, policy_arn: policy.policy_arn)
      @iam_client.delete_policy(policy_arn: policy.policy_arn)
      @logger.info("Detached and deleted policy #{policy.policy_name}.")
    end
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Role deleted: #{role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't detach policies and delete role #{role.name}. Here's why:")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Deletes a user. If the user has inline policies or access keys, they are deleted
  # before the user is deleted.
  #
  # @param user [Aws::IAM::User] The user to delete.
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
end

# Runs the IAM create a user and assume a role scenario.
def run_scenario(scenario)
  puts('-' * 88)
  puts('Welcome to the IAM create a user and assume a role demo!')
  puts('-' * 88)
  user = scenario.create_user("doc-example-user-#{Random.uuid}")
  user_key = scenario.create_access_key_pair(user)
  scenario.wait(10)
  role = scenario.create_role("doc-example-role-#{Random.uuid}", user)
  scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role)
  scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role)
  scenario.wait(10)
  puts('Try to list buckets with credentials for a user who has no permissions.')
  puts('Expect AccessDenied from this call.')
  scenario.list_buckets(
    scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))
  )
  puts('Now, assume the role that grants permission.')
  temp_credentials = scenario.assume_role(
    role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)
  )
  puts('Here are your buckets:')
  scenario.list_buckets(scenario.create_s3_resource(temp_credentials))
  puts("Deleting role '#{role.role_name}' and attached policies.")
  scenario.delete_role(role.role_name)
  puts("Deleting user '#{user.user_name}', policies, and keys.")
  scenario.delete_user(user.user_name)
  puts('Thanks for watching!')
  puts('-' * 88)
rescue Aws::Errors::ServiceError => e
  puts('Something went wrong with the demo.')
  puts("\t#{e.code}: #{e.message}")
end

run_scenario(ScenarioCreateUserAssumeRole.new(Aws::IAM::Client.new)) if $PROGRAM_NAME == __FILE__
```
+ For API details, see the following topics in *AWS SDK for Ruby API Reference*.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Rust ]

**SDK for Rust**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples). 

```
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iam::Error as iamError;
use aws_sdk_iam::{config::Credentials as iamCredentials, config::Region, Client as iamClient};
use aws_sdk_s3::Client as s3Client;
use aws_sdk_sts::Client as stsClient;
use tokio::time::{sleep, Duration};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), iamError> {
    let (client, uuid, list_all_buckets_policy_document, inline_policy_document) =
        initialize_variables().await;

    if let Err(e) = run_iam_operations(
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
    .await
    {
        println!("{:?}", e);
    };

    Ok(())
}

async fn initialize_variables() -> (iamClient, String, String, String) {
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = iamClient::new(&shared_config);
    let uuid = Uuid::new_v4().to_string();

    let list_all_buckets_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
    }"
    .to_string();
    let inline_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{}\"}]
    }"
    .to_string();

    (
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
}

async fn run_iam_operations(
    client: iamClient,
    uuid: String,
    list_all_buckets_policy_document: String,
    inline_policy_document: String,
) -> Result<(), iamError> {
    let user = iam_service::create_user(&client, &format!("{}{}", "iam_demo_user_", uuid)).await?;
    println!("Created the user with the name: {}", user.user_name());
    let key = iam_service::create_access_key(&client, user.user_name()).await?;

    let assume_role_policy_document = "{
        \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }"
    .to_string()
    .replace("{}", user.arn());

    let assume_role_role = iam_service::create_role(
        &client,
        &format!("{}{}", "iam_demo_role_", uuid),
        &assume_role_policy_document,
    )
    .await?;
    println!("Created the role with the ARN: {}", assume_role_role.arn());

    let list_all_buckets_policy = iam_service::create_policy(
        &client,
        &format!("{}{}", "iam_demo_policy_", uuid),
        &list_all_buckets_policy_document,
    )
    .await?;
    println!(
        "Created policy: {}",
        list_all_buckets_policy.policy_name.as_ref().unwrap()
    );

    let attach_role_policy_result =
        iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy)
            .await?;
    println!(
        "Attached the policy to the role: {:?}",
        attach_role_policy_result
    );

    let inline_policy_name = format!("{}{}", "iam_demo_inline_policy_", uuid);
    let inline_policy_document = inline_policy_document.replace("{}", assume_role_role.arn());
    iam_service::create_user_policy(&client, &user, &inline_policy_name, &inline_policy_document)
        .await?;
    println!("Created inline policy.");

    //First, fail to list the buckets with the user.
    let creds = iamCredentials::from_keys(key.access_key_id(), key.secret_access_key(), None);
    let fail_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    println!("Fail config: {:?}", fail_config);
    let fail_client: s3Client = s3Client::new(&fail_config);
    match fail_client.list_buckets().send().await {
        Ok(e) => {
            println!("This should not run. {:?}", e);
        }
        Err(e) => {
            println!("Successfully failed with error: {:?}", e)
        }
    }

    let sts_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    let sts_client: stsClient = stsClient::new(&sts_config);
    sleep(Duration::from_secs(10)).await;
    let assumed_role = sts_client
        .assume_role()
        .role_arn(assume_role_role.arn())
        .role_session_name(format!("iam_demo_assumerole_session_{uuid}"))
        .send()
        .await;
    println!("Assumed role: {:?}", assumed_role);
    sleep(Duration::from_secs(10)).await;

    let assumed_credentials = iamCredentials::from_keys(
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .access_key_id(),
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .secret_access_key(),
        Some(
            assumed_role
                .as_ref()
                .unwrap()
                .credentials
                .as_ref()
                .unwrap()
                .session_token
                .clone(),
        ),
    );

    let succeed_config = aws_config::from_env()
        .credentials_provider(assumed_credentials)
        .load()
        .await;
    println!("succeed config: {:?}", succeed_config);
    let succeed_client: s3Client = s3Client::new(&succeed_config);
    sleep(Duration::from_secs(10)).await;
    match succeed_client.list_buckets().send().await {
        Ok(_) => {
            println!("This should now run successfully.")
        }
        Err(e) => {
            println!("This should not run. {:?}", e);
            panic!()
        }
    }

    //Clean up.
    iam_service::detach_role_policy(
        &client,
        assume_role_role.role_name(),
        list_all_buckets_policy.arn().unwrap_or_default(),
    )
    .await?;
    iam_service::delete_policy(&client, list_all_buckets_policy).await?;
    iam_service::delete_role(&client, &assume_role_role).await?;
    println!("Deleted role {}", assume_role_role.role_name());
    iam_service::delete_access_key(&client, &user, &key).await?;
    println!("Deleted key for {}", key.user_name());
    iam_service::delete_user_policy(&client, &user, &inline_policy_name).await?;
    println!("Deleted inline user policy: {}", inline_policy_name);
    iam_service::delete_user(&client, &user).await?;
    println!("Deleted user {}", user.user_name());

    Ok(())
}
```
+ For API details, see the following topics in *AWS SDK for Rust API reference*.
  + [AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)
  + [CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)
  + [CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)
  + [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)
  + [CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)
  + [DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)
  + [DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)
  + [DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)
  + [DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)
  + [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)
  + [DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)
  + [PutUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.put_user_policy)

------

# Use an IAM role to grant permissions to applications running on Amazon EC2 instances
Use roles for applications on Amazon EC2

Applications that run on an Amazon EC2 instance must include AWS credentials in the AWS API requests. You could have your developers store AWS credentials directly within the Amazon EC2 instance and allow applications in that instance to use those credentials. But developers would then have to manage the credentials and ensure that they securely pass the credentials to each instance and update each Amazon EC2 instance when it's time to update the credentials. That's a lot of additional work.

Instead, you can and should use an IAM role to manage *temporary* credentials for applications that run on an Amazon EC2 instance. When you use a role, you don't have to distribute long-term credentials (such as sign-in credentials or access keys) to an Amazon EC2 instance. Instead, the role supplies temporary permissions that applications can use when they make calls to other AWS resources. When you launch an Amazon EC2 instance, you specify an IAM role to associate with the instance. Applications that run on the instance can then use the role-supplied temporary credentials to sign API requests.

Using roles to grant permissions to applications that run on Amazon EC2 instances requires a bit of extra configuration. An application running on an Amazon EC2 instance is abstracted from AWS by the virtualized operating system. Because of this extra separation, you need an additional step to assign an AWS role and its associated permissions to an Amazon EC2 instance and make them available to its applications. This extra step is the creation of an *[instance profile](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)* attached to the instance. The instance profile contains the role and can provide the role's temporary credentials to an application that runs on the instance. Those temporary credentials can then be used in the application's API calls to access resources and to limit access to only those resources that the role specifies.

**Note**  
Only one role can be assigned to an Amazon EC2 instance at a time, and all applications on the instance share the same role and permissions. When you leverage Amazon ECS to manage your Amazon EC2 instances, you can assign roles to Amazon ECS tasks that can be distinguished from the role of the Amazon EC2 instance that it's running on. Assigning each task a role aligns with the principle of least privileged access and allows for greater granular control over actions and resources.  
For more information, see [Using IAM roles with Amazon ECS tasks](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-iam-roles.html) in the *Amazon Elastic Container Service Best Practices Guide*.

Using roles in this way has several benefits. Because role credentials are temporary and updated automatically, you don't have to manage credentials, and you don't have to worry about long-term security risks. In addition, if you use a single role for multiple instances, you can make a change to that one role and the change propagates automatically to all the instances. 

**Note**  
Although a role is usually assigned to an Amazon EC2 instance when you launch it, a role can also be attached to an Amazon EC2 instance currently running. To learn how to attach a role to a running instance, see [IAM Roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role).

**Topics**
+ [

## How do roles for Amazon EC2 instances work?
](#roles-usingrole-ec2instance-roles)
+ [

## Permissions required for using roles with Amazon EC2
](#roles-usingrole-ec2instance-permissions)
+ [

## How do I get started?
](#roles-usingrole-ec2instance-get-started)
+ [

## Related information
](#roles-usingrole-ec2instance-related-info)

## How do roles for Amazon EC2 instances work?


In the following figure, a developer runs an application on an Amazon EC2 instance that requires access to the S3 bucket named `amzn-s3-demo-bucket-photos`. An administrator creates the `Get-pics` service role and attaches the role to the Amazon EC2 instance. The role includes a permissions policy that grants read-only access to the specified S3 bucket. It also includes a trust policy that allows the Amazon EC2 instance to assume the role and retrieve the temporary credentials. When the application runs on the instance, it can use the role's temporary credentials to access the photos bucket. The administrator doesn't have to grant the developer permission to access the photos bucket, and the developer never has to share or manage credentials.

![\[Application on an Amazon EC2 instance accessing an AWS resource\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/roles-usingrole-ec2roleinstance.png)


1. The administrator uses IAM to create the **Get-pics** role. In the role's trust policy, the administrator specifies that only Amazon EC2 instances can assume the role. In the role's permission policy, the administrator specifies read-only permissions for the `amzn-s3-demo-bucket-photos` bucket.

1. A developer launches an Amazon EC2 instance and assigns the `Get-pics` role to that instance.
**Note**  
If you use the IAM console, the instance profile is managed for you and is mostly transparent to you. However, if you use the AWS CLI or API to create and manage the role and Amazon EC2 instance, then you must create the instance profile and assign the role to it as separate steps. Then, when you launch the instance, you must specify the instance profile name instead of the role name.

1. When the application runs, it obtains temporary security credentials from Amazon EC2 [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html), as described in [Retrieving Security Credentials from Instance Metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials). These are [temporary security credentials](id_credentials_temp.md) that represent the role and are valid for a limited period of time. 

   With some [AWS SDKs](https://aws.amazon.com/tools/), the developer can use a provider that manages the temporary security credentials transparently. (The documentation for individual AWS SDKs describes the features supported by that SDK for managing credentials.)

   Alternatively, the application can get the temporary credentials directly from the instance metadata of the Amazon EC2 instance. Credentials and related values are available from the `iam/security-credentials/role-name` category (in this case, `iam/security-credentials/Get-pics`) of the metadata. If the application gets the credentials from the instance metadata, it can cache the credentials.

1. Using the retrieved temporary credentials, the application accesses the photo bucket. Because of the policy attached to the **Get-pics** role, the application has read-only permissions. 

   The temporary security credentials available on the instance automatically update before they expire so that a valid set is always available. The application just needs to make sure that it gets a new set of credentials from the instance metadata before the current ones expire. It is possible to use the AWS SDK to manage credentials so the application does not need to include additional logic to refresh the credentials. For example, instantiating clients with Instance Profile Credential Providers. However, if the application gets temporary security credentials from the instance metadata and has cached them, it should get a refreshed set of credentials every hour, or at least 15 minutes before the current set expires. The expiration time is included in the information returned in the `iam/security-credentials/role-name` category. 

## Permissions required for using roles with Amazon EC2


To launch an instance with a role, the developer must have permission to launch Amazon EC2 instances and permission to pass IAM roles.

The following sample policy allows users to use the AWS Management Console to launch an instance with a role. The policy includes wildcards (`*`) to allow a user to pass any role and to perform the listed Amazon EC2 actions. The `ListInstanceProfiles` action allows users to view all of the roles available in the AWS account.

**Example policy that grants a user permission to use the Amazon EC2 console to launch an instance with any role**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "IamPassRole",
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "ec2.amazonaws.com"
                }
            }
        },
        {
            "Sid": "ListEc2AndListInstanceProfiles",
            "Effect": "Allow",
            "Action": [
                "iam:ListInstanceProfiles",
                "ec2:Describe*",
                "ec2:Search*",
                "ec2:Get*"
            ],
            "Resource": "*"
        }
    ]
}
```

### Restricting which roles can be passed to Amazon EC2 instances (using PassRole)


You can use the `PassRole` permission to restrict which role a user can pass to an Amazon EC2 instance when the user launches the instance. This helps prevent the user from running applications that have more permissions than the user has been granted—that is, from being able to obtain elevated privileges. For example, imagine that user Alice has permissions only to launch Amazon EC2 instances and to work with Amazon S3 buckets, but the role she passes to an Amazon EC2 instance has permissions to work with IAM and Amazon DynamoDB. In that case, Alice might be able to launch the instance, log into it, get temporary security credentials, and then perform IAM or DynamoDB actions that she's not authorized for.

To restrict which roles a user can pass to an Amazon EC2 instance, you create a policy that allows the `PassRole` action. You then attach the policy to the user (or to an IAM group that the user belongs to) who will launch Amazon EC2 instances. In the `Resource` element of the policy, you list the role or roles that the user is allowed to pass to Amazon EC2 instances. When the user launches an instance and associates a role with it, Amazon EC2 checks whether the user is allowed to pass that role. Of course, you should also ensure that the role that the user can pass does not include more permissions than the user is supposed to have.

**Note**  
`PassRole` is not an API action in the same way that `RunInstances` or `ListInstanceProfiles` is. Instead, it's a permission that AWS checks whenever a role ARN is passed as a parameter to an API (or the console does this on the user's behalf). It helps an administrator to control which roles can be passed by which users. In this case, it ensures that the user is allowed to attach a specific role to an Amazon EC2 instance.

**Example policy that grants a user permission to launch an Amazon EC2 instance with a specific role**  
The following sample policy allows users to use the Amazon EC2 API to launch an instance with a role. The `Resource` element specifies the Amazon Resource Name (ARN) of a role. By specifying the ARN, the policy grants the user the permission to pass only the `Get-pics` role. If the user tries to specify a different role when launching an instance, the action fails. The user does have permissions to run any instance, regardless of whether they pass a role.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:RunInstances",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/Get-pics"
        }
    ]
}
```

### Allowing an instance profile role to switch to a role in another account


You can allow an application running on an Amazon EC2 instance to run commands in another account. To do this, you must allow the Amazon EC2 instance role in the first account to switch to a role in the second account.

Imagine that you are using two AWS accounts and you want to allow an application running on an Amazon EC2 instance to run [AWS CLI](https://aws.amazon.com/cli/) commands in both accounts. Assume that the Amazon EC2 instance exists in account `111111111111`. That instance includes the `abcd` instance profile role that allows the application to perform read-only Amazon S3 tasks on the `amzn-s3-demo-bucket1` bucket within the same `111111111111` account. However, the application must also be allowed to assume the `efgh` cross-account role to access the `amzn-s3-demo-bucket2` Amazon S3 bucket in account `222222222222`.

![\[The diagram shows how a developer launches an Amazon EC2 instance with the role to get access to photos in an Amazon S3 bucket.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/roles-instance-profile-cross-account.png)


The `abcd` Amazon EC2 instance profile role must have the following permissions policy to allow the application to access the `amzn-s3-demo-bucket1` Amazon S3 bucket:

***Account 111111111111 `abcd` Role Permissions Policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1/*",
                "arn:aws:s3:::amzn-s3-demo-bucket1"
            ]
        },
        {
            "Sid": "AllowIPToAssumeCrossAccountRole",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::222222222222:role/efgh"
        }
    ]
}
```

------

The `abcd` role must trust the Amazon EC2 service to assume the role. To do this, the `abcd` role must have the following trust policy:

***Account 111111111111 `abcd` Role Trust Policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "abcdTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"Service": "ec2.amazonaws.com"}
        }
    ]
}
```

------

Assume that the `efgh` cross-account role allows read-only Amazon S3 tasks on the `amzn-s3-demo-bucket2` bucket within the same `222222222222` account. To do this, the `efgh` cross-account role must have the following permissions policy:

***Account 222222222222 `efgh` Role Permissions Policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket2/*",
                "arn:aws:s3:::amzn-s3-demo-bucket2"
            ]
        }
    ]
}
```

------

The `efgh` role must trust the `abcd` instance profile role to assume it. To do this, the `efgh` role must have the following trust policy:

***Account 222222222222 `efgh` Role Trust Policy***

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "efghTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"AWS": "arn:aws:iam::111111111111:role/abcd"}
        }
    ]
}
```

------

## How do I get started?


To understand how roles work with Amazon EC2 instances, you need to use the IAM console to create a role, launch an Amazon EC2 instance that uses that role, and then examine the running instance. You can examine the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) to see how the role's temporary credentials are made available to an instance. You can also see how an application that runs on an instance can use the role. Use the following resources to learn more. 
+ [IAM Roles on Amazon EC2 Instances Tutorial](https://www.youtube.com/watch?v=TlCuOjviOhk). The linked video shows how to use an IAM role with an Amazon EC2 instance to control what an application can do when it runs on the instance. The video shows how the application (written in the AWS SDK) can get temporary security credentials through the role. 
+ SDK walkthroughs. The AWS SDK documentation includes walkthroughs that show an application running on an Amazon EC2 instance that uses temporary credentials for roles to read an Amazon S3 bucket. Each of the following walkthroughs presents similar steps with a different programming language:
  + [Configure IAM Roles for Amazon EC2 with the SDK for Java](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java-dg-roles.html) in the *AWS SDK for Java Developer Guide* 
  + [Launch an Amazon EC2 Instance using the SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/run-instance.html) in the *AWS SDK for .NET Developer Guide*
  + [Creating an Amazon EC2 Instance with the SDK for Ruby](https://docs.aws.amazon.com/sdk-for-ruby/latest/developer-guide/ec2-example-create-instance.html) in the *AWS SDK for Ruby Developer Guide*

## Related information


For more information about creating roles or roles for Amazon EC2 instances, see the following information:
+ For more information about [using IAM roles with Amazon EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html), go to the *Amazon EC2 User Guide*.
+ To create a role, see [IAM role creation](id_roles_create.md)
+ For more information about using temporary security credentials, see [Temporary security credentials in IAM](id_credentials_temp.md).
+ If you work with the IAM API or CLI, you must create and manage IAM instance profiles. For more information about instance profiles, see [Use instance profiles](id_roles_use_switch-role-ec2_instance-profiles.md).
+ For more information about temporary security credentials for roles in the instance metadata, see [Retrieving Security Credentials from Instance Metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials) in the *Amazon EC2 User Guide*.

# Use instance profiles


Use an instance profile to pass an IAM role to an EC2 instance. 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*.

## Managing instance profiles (console)


If you use the AWS Management Console to create a role for Amazon EC2, the console automatically creates an instance profile and gives it the same name as the role. When you then use the Amazon EC2 console to launch an instance with an IAM role, you can select a role to associate with the instance. In the console, the list that's displayed is actually a list of instance profile names. The console does not create an instance profile for a role that is not associated with Amazon EC2.

You can use the AWS Management Console to delete IAM roles and instance profiles for Amazon EC2 if the role and the instance profile have the same name. To learn more about deleting instance profiles, see [Delete roles or instance profiles](id_roles_manage_delete.md).

**Note**  
To update permissions for an instance, replace its instance profile. We do not recommend removing a role from an instance profile, because there is a delay of up to one hour before this change takes effect.

## Managing instance profiles (AWS CLI or AWS API)


If you manage your roles from the AWS CLI or the AWS API, you create roles and instance profiles as separate actions. Because roles and instance profiles can have different names, you must know the names of your instance profiles as well as the names of roles they contain. That way you can choose the correct instance profile when you launch an EC2 instance. 

You can attach tags to your IAM resources, including instance profiles, to identify, organize, and control access to them. You can tag instance profiles only when you use the AWS CLI or AWS API. 

**Note**  
An instance profile can contain only one IAM role, although a role can be included in multiple instance profiles. This limit of one role per instance profile cannot be increased. You can remove the existing role and then add a different role to an instance profile. You must then wait for the change to appear across all of AWS because of [eventual consistency](https://en.wikipedia.org/wiki/Eventual_consistency). To force the change, you must [disassociate the instance profile](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html) and then [associate the instance profile](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html), or you can stop your instance and then restart it.

### Managing instance profiles (AWS CLI)


You can use the following AWS CLI commands to work with instance profiles in an AWS account. 
+ Create an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html)
+ Tag an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/tag-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-instance-profile.html)
+ List tags for an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profile-tags.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profile-tags.html)
+ Untag an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/untag-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-instance-profile.html)
+ Add a role to an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html) 
+ List instance profiles: [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html), [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles-for-role.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles-for-role.html) 
+ Get information about an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/get-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-instance-profile.html) 
+ Remove a role from an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/remove-role-from-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-role-from-instance-profile.html)
+ Delete an instance profile: [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-instance-profile.html) 

You can also attach a role to an already running EC2 instance by using the following commands. For more information, see [IAM Roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role).
+ Attach an instance profile with a role to a stopped or running EC2 instance: [https://docs.aws.amazon.com/cli/latest/reference/ec2/associate-iam-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/associate-iam-instance-profile.html) 
+ Get information about an instance profile attached to an EC2 instance: [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html) 
+ Detach an instance profile with a role from a stopped or running EC2 instance: [https://docs.aws.amazon.com/cli/latest/reference/ec2/disassociate-iam-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/disassociate-iam-instance-profile.html) 

### Managing instance profiles (AWS API)


You can call the following AWS API operations to work with instance profiles in an AWS account.
+ Create an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html) 
+ Tag an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html) 
+ List tags on an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html) 
+ Untag an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html) 
+ Add a role to an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html) 
+ List instance profiles: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html), [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html) 
+ Get information about an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetInstanceProfile.html) 
+ Remove a role from an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html) 
+ Delete an instance profile: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html) 

You can also attach a role to an already running EC2 instance by calling the following operations. For more information, see [IAM Roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role).
+ Attach an instance profile with a role to a stopped or running EC2 instance: [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html) 
+ Get information about an instance profile attached to an EC2 instance: [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeIamInstanceProfileAssociations.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeIamInstanceProfileAssociations.html) 
+ Detach an instance profile with a role from a stopped or running EC2 instance: [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html) 

# Identity providers and federation into AWS


As a best practice, we recommend that you require human users to use federation with an identity provider to access AWS resources instead of creating individual IAM users in your AWS account. With an identity provider (IdP), you can manage your user identities outside of AWS and give these external user identities permissions to use AWS resources in your account. This is useful if your organization already has its own identity system, such as a corporate user directory. It is also useful if you are creating a mobile app or web application that requires access to AWS resources.

**Note**  
You can also manage human users in [IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/what-is.html) with an external SAML identity provider instead of using SAML federation in IAM. IAM Identity Center federation with an identity provider provides the capability for you to give people access to multiple AWS accounts in your organization and to multiple AWS applications. For information about specific situations where an IAM user is required, see [When to create an IAM user (instead of a role)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_which-to-choose).

If you prefer to use a single AWS account without enabling IAM Identity Center, you can use IAM with an external IdP that provides identity information to AWS using either [OpenID Connect (OIDC)](http://openid.net/connect/) or [SAML 2.0 (Security Assertion Markup Language 2.0)](https://wiki.oasis-open.org/security). OIDC connects applications, like GitHub Actions, that do not run on AWS to AWS resources. Examples of well-known SAML identity providers are Shibboleth and Active Directory Federation Services.

When you use an identity provider, you don't have to create custom sign-in code or manage your own user identities. The IdP provides that for you. Your external users sign in through an IdP, and you can give those external identities permissions to use AWS resources in your account. Identity providers help keep your AWS account secure because you don't have to distribute or embed long-term security credentials, such as access keys, in your application.

Review the following table to help determine which IAM federation type is best for your use case; IAM, IAM Identity Center, or Amazon Cognito. The following summaries and table provide an overview of the methods that your users can employ to gain federated access to AWS resources.


| IAM federation type | Account type | Access management of.. | Supported identity source | 
| --- | --- | --- | --- | 
|  Federation with IAM Identity Center  |  Multiple accounts managed by AWS Organizations  |  Your workforce’s human users  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)  | 
|  Federation with IAM  |  Single, standalone account  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)  | 
|  Federation with Amazon Cognito identity pools  |  Any  |  The users of apps that require IAM authorization to access resources  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)  | 

## Federation with IAM Identity Center


For centralized access management of human users, we recommend that you use [IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) to manage access to your accounts and permissions within those accounts. Users in IAM Identity Center are granted short-term credentials to your AWS resources. You can use Active Directory, an external identity provider (IdP), or an IAM Identity Center directory as the identity source for users and groups to assign access to your AWS resources. 

IAM Identity Center supports identity federation with SAML (Security Assertion Markup Language) 2.0 to provide federated single sign-on access for users who are authorized to use applications within the AWS access portal. Users can then single sign-on into services that support SAML, including the AWS Management Console and third-party applications, such as Microsoft 365, SAP Concur, and Salesforce.

## Federation with IAM


While we strongly recommend managing human users in IAM Identity Center, you can enable federated principal access with IAM for human users in short-term, small scale deployments. IAM allows you to use separate SAML 2.0 and Open ID Connect (OIDC) IdPs and use federated principal attributes for access control. With IAM, you can pass user attributes, such as cost center, title, or locale, from your IdPs to AWS, and implement fine-grained access permissions based on these attributes.

A *workload* is a collection of resources and code that delivers business value, such as an application or backend process. Your workload can require an IAM identity to make requests to AWS services, applications, operational tools, and components. These identities include machines running in your AWS environments, such as Amazon EC2 instances or AWS Lambda functions.

You can also manage machine identities for external parties who need access. To give access to machine identities, you can use IAM roles. IAM roles have specific permissions and provide a way to access AWS by relying on temporary security credentials with a role session. Additionally, you might have machines outside of AWS that need access to your AWS environments. For machines that run outside of AWS you can use [IAM Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/introduction.html). For more information about roles, see [IAM roles](id_roles.md). For details about how to use roles to delegate access across AWS accounts, see [IAM tutorial: Delegate access across AWS accounts using IAM roles](tutorial_cross-account-with-roles.md).

To link an IdP directly to IAM, you create an identity provider entity to establish a trust relationship between your AWS account and the IdP. IAM supports IdPs that are compatible with [OpenID Connect (OIDC)](http://openid.net/connect/) or [SAML 2.0 (Security Assertion Markup Language 2.0)](https://wiki.oasis-open.org/security). For more information about using one of these IdPs with AWS, see the following sections:
+ [OIDC federation](id_roles_providers_oidc.md)
+ [SAML 2.0 federation](id_roles_providers_saml.md)

## Federation with Amazon Cognito identity pools


Amazon Cognito is designed for developers who want to authenticate and authorize users in their mobile and web apps. Amazon Cognito user pools add sign-in and sign-up features to your app, and identity pools deliver IAM credentials that grant your users access to protected resources that you manage in AWS. Identity pools acquire credentials for temporary sessions through the [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation.

Amazon Cognito works with external identity providers that support SAML and OpenID Connect, and with social identity providers like Facebook, Google, and Amazon. Your app can sign in a user with a user pool or an external IdP, then retrieve resources on their behalf with customized temporary sessions in an IAM role.

## Additional resources

+ For a demonstration on how to create a custom federation proxy that enables single sign-on (SSO) into the AWS Management Console using your organization's authentication system, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).

# Common scenarios


**Note**  
We recommend that you require your human users to use temporary credentials when accessing AWS. Have you considered using AWS IAM Identity Center? You can use IAM Identity Center to centrally manage access to multiple AWS accounts and provide users with MFA-protected, single sign-on access to all their assigned accounts from one place. With IAM Identity Center, you can create and manage user identities in IAM Identity Center or easily connect to your existing SAML 2.0 compatible identity provider. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the *AWS IAM Identity Center User Guide*.

You can use an external identity provider (IdP) to manage user identities outside of AWS and the external IdP. An external IdP can provide identity information to AWS using either OpenID Connect (OIDC) or Security Assertion Markup Language (SAML). OIDC is commonly used when an application that does not run on AWS needs access to AWS resources.

When you want to configure federation with an external IdP, you create an IAM *identity provider* to inform AWS about the external IdP and its configuration. This establishes trust between your AWS account and the external IdP. The following topics provide common scenarios to use IAM identity providers.

**Topics**
+ [

## Amazon Cognito for mobile apps
](#id_roles_providers_oidc_cognito)
+ [

## OIDC federation for mobile apps
](#id_roles_providers_oidc_manual)

## Amazon Cognito for mobile apps


The preferred way to use OIDC federation is to use [Amazon Cognito](https://aws.amazon.com/cognito/). For example, Adele the developer is building a game for a mobile device where user data such as scores and profiles is stored in Amazon S3 and Amazon DynamoDB. Adele could also store this data locally on the device and use Amazon Cognito to keep it synchronized across devices. She knows that for security and maintenance reasons, long-term AWS security credentials should not be distributed with the game. She also knows that the game might have a large number of users. For all of these reasons, she does not want to create new user identities in IAM for each player. Instead, she builds the game so that users can sign in using an identity that they've already established with a well-known external identity provider (IdP), such as **Login with Amazon**, **Facebook**, **Google**, or any **OpenID Connect** (OIDC)-compatible IdP. Her game can take advantage of the authentication mechanism from one of these providers to validate the user's identity. 

To enable the mobile app to access her AWS resources, Adele first registers for a developer ID with her chosen IdPs. She also configures the application with each of these providers. In her AWS account that contains the Amazon S3 bucket and DynamoDB table for the game, Adele uses Amazon Cognito to create IAM roles that precisely define permissions that the game needs. If she is using an OIDC IdP, she also creates an IAM OIDC identity provider entity to establish trust between an [Amazon Cognito identity pool](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) in her AWS account and the IdP.

In the app's code, Adele calls the sign-in interface for the IdP that she configured previously. The IdP handles all the details of letting the user sign in, and the app gets an OAuth access token or OIDC ID token from the provider. Adele's app can trade this authentication information for a set of temporary security credentials that consist of an AWS access key ID, a secret access key, and a session token. The app can then use these credentials to access web services offered by AWS. The app is limited to the permissions that are defined in the role that it assumes.

The following figure shows a simplified flow for how this might work, using Login with Amazon as the IdP. For Step 2, the app can also use Facebook, Google, or any OIDC-compatible IdP, but that's not shown here.

![\[Sample workflow using Amazon Cognito to federate users for a mobile application\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/mobile-app-web-identity-federation.diagram.png)


 

1. A customer starts your app on a mobile device. The app asks the user to sign in.

1. The app uses Login with Amazon resources to accept the user's credentials.

1. The app uses the Amazon Cognito API operations `GetId` and `GetCredentialsForIdentity` to exchange the Login with Amazon ID token for an Amazon Cognito token. Amazon Cognito, which has been configured to trust your Login with Amazon project, generates a token that it exchanges for temporary session credentials with AWS STS.

1. The app receives temporary security credentials from Amazon Cognito. Your app can also use the Basic (Classic) workflow in Amazon Cognito to retrieve tokens from AWS STS using `AssumeRoleWithWebIdentity`. For more information, see [Identity pools (federated identities) authentication flow](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html) in the Amazon Cognito Developer Guide.

1. The temporary security credentials can be used by the app to access any AWS resources required by the app to operate. The role associated with the temporary security credentials and the assigned policies determines what can be accessed.

Use the following process to configure your app to use Amazon Cognito to authenticate users and give your app access to AWS resources. For specific steps to accomplish this scenario, consult the documentation for Amazon Cognito.

1. (Optional) Sign up as a developer with Login with Amazon, Facebook, Google, or any other OpenID Connect (OIDC)–compatible IdP and configure one or more apps with the provider. This step is optional because Amazon Cognito also supports unauthenticated (guest) access for your users.

1. Go to [Amazon Cognito in the AWS Management Console](https://console.aws.amazon.com/cognito/home). Use the Amazon Cognito wizard to create an identity pool, which is a container that Amazon Cognito uses to keep end user identities organized for your apps. You can share identity pools between apps. When you set up an identity pool, Amazon Cognito creates one or two IAM roles (one for authenticated identities, and one for unauthenticated "guest" identities) that define permissions for Amazon Cognito users. 

1. Integrate [AWS](https://docs.amplify.aws)Amplify with your app, and import the files required to use Amazon Cognito.

1. Create an instance of the Amazon Cognito credentials provider, passing the identity pool ID, your AWS account number, and the Amazon Resource Name (ARN) of the roles that you associated with the identity pool. The Amazon Cognito wizard in the AWS Management Console provides sample code to help you get started.

1. When your app accesses an AWS resource, pass the credentials provider instance to the client object, which passes temporary security credentials to the client. The permissions for the credentials are based on the role or roles that you defined earlier.

For more information, see the following:
+ [Sign in (Android)](https://docs.amplify.aws/lib/auth/signin/q/platform/android/) in the AWS Amplify Framework Documentation. 
+ [Sign in (iOS)](https://docs.amplify.aws/lib/auth/signin/q/platform/ios/) in the AWS Amplify Framework Documentation.

## OIDC federation for mobile apps


For best results, use Amazon Cognito as your identity broker for almost all OIDC federation scenarios. Amazon Cognito is easy to use and provides additional capabilities like anonymous (unauthenticated) access, and synchronizing user data across devices and providers. However, if you have already created an app that uses OIDC federation by manually calling the `AssumeRoleWithWebIdentity` API, you can continue to use it and your apps will still work fine. 

The process for using OIDC federation ***without*** Amazon Cognito follows this general outline: 

1. Sign up as a developer with the external identity provider (IdP) and configure your app with the IdP, who gives you a unique ID for your app. (Different IdPs use different terminology for this process. This outline uses the term *configure* for the process of identifying your app with the IdP.) Each IdP gives you an app ID that's unique to that IdP, so if you configure the same app with multiple IdPs, your app will have multiple app IDs. You can configure multiple apps with each provider. 

   The following external links provide information about using some of the commonly used identity providers (IdPs): 
   + [Login with Amazon Developer Center](https://login.amazon.com/) 
   + [Add Facebook Login to Your App or Website](https://developers.facebook.com/docs/facebook-login/v2.1) on the Facebook developers site. 
   + [Using OAuth 2.0 for Login (OpenID Connect)](https://developers.google.com/accounts/docs/OAuth2Login) on the Google developers site.
**Important**  
If you use an OIDC identity provider from Google, Facebook, or Amazon Cognito, do not create a separate IAM identity provider in the AWS Management Console. AWS has these OIDC identity providers built-in and available for your use. Skip the following step and move directly to creating new roles using your identity provider.

1. If you use an IdP other than Google, Facebook or Amazon Cognito compatible with OIDC, then create an IAM identity provider entity for it.

1. In IAM, [create one or more roles](id_roles_create_for-idp.md). For each role, define who can assume the role (the trust policy) and what permissions the app's users have (the permissions policy). Typically, you create one role for each IdP that an app supports. For example, you might create a role assumed by an app if the user signs in through Login with Amazon, a second role for the same app if the user signs in through Facebook, and a third role for the app if the user signs in through Google. For the trust relationship, specify the IdP (like Amazon.com) as the `Principal` (the trusted entity), and include a `Condition` that matches the IdP assigned app ID. Examples of roles for different providers are described in [Create a role for a third-party identity provider](id_roles_create_for-idp.md). 

1. In your application, authenticate your users with the IdP. The specifics of how to do this vary both according to which IdP you use (Login with Amazon, Facebook, or Google) and on which platform your app runs. For example, an Android app's method of authentication can differ from that of an iOS app or a JavaScript-based web app.

   Typically, if the user is not already signed in, the IdP takes care of displaying a sign-in page. After the IdP authenticates the user, the IdP returns an authentication token with information about the user to your app. The information included depends on what the IdP exposes and what information the user is willing to share. You can use this information in your app.

1. In your app, make an *unsigned* call to the `AssumeRoleWithWebIdentity` action to request temporary security credentials. In the request, you pass the IdP's authentication token and specify the Amazon Resource Name (ARN) for the IAM role that you created for that IdP. AWS verifies that the token is trusted and valid and if so, returns temporary security credentials to your app that have the permissions for the role that you name in the request. The response also includes metadata about the user from the IdP, such as the unique user ID that the IdP associates with the user.

1. Using the temporary security credentials from the `AssumeRoleWithWebIdentity` response, your app makes signed requests to AWS API operations. The user ID information from the IdP can distinguish users in your app. For example, you can put objects into Amazon S3 folders that include the user ID as prefixes or suffixes. This lets you create access control policies that lock the folder so only the user with that ID can access it. For more information, see [AWS STS federated user principals](reference_policies_elements_principal.md#sts-session-principals).

1. Your app should cache the temporary security credentials so that you do not have to get new ones each time the app needs to make a request to AWS. By default, the credentials are good for one hour. When the credentials expire (or before then), you make another call to `AssumeRoleWithWebIdentity` to obtain a new set of temporary security credentials. Depending on the IdP and how they manage their tokens, you might have to refresh the IdP's token before you make a new call to `AssumeRoleWithWebIdentity`, since the IdP's tokens also usually expire after a fixed time. If you use the AWS SDK for iOS or the AWS SDK for Android, you can use the [AmazonSTSCredentialsProvider](https://aws.amazon.com/blogs/mobile/using-the-amazoncredentialsprovider-protocol-in-the-aws-sdk-for-ios) action, which manages the IAM temporary credentials, including refreshing them as required.

# OIDC federation
OIDC federation

Imagine that you are creating an application that accesses AWS resources, such as GitHub Actions that uses workflows to access Amazon S3 and DynamoDB. 

When you use these workflows, you make requests to AWS services that must be signed with an AWS access key. However, we **strongly** recommend that you do **not** store AWS credentials long-term in applications outside AWS. Instead, configure your applications to request temporary AWS security credentials dynamically when needed using *OIDC federation*. The supplied temporary credentials map to an AWS role that only has permissions needed to perform the tasks required by the application.

With OIDC federation, you don't need to create custom sign-in code or manage your own user identities. Instead, you can use OIDC in applications, such as GitHub Actions or any other [OpenID Connect (OIDC)](http://openid.net/connect/)-compatible IdP, to authenticate with AWS. They receive an authentication token, known as a JSON Web Token (JWT), and then exchange that token for temporary security credentials in AWS that map to an IAM role with permissions to use specific resources in your AWS account. Using an IdP helps you keep your AWS account secure because you don't have to embed and distribute long-term security credentials with your application.

OIDC federation supports both machine-to-machine authentication (such as CI/CD pipelines, automated scripts, and serverless applications) and human user authentication. For human user authentication scenarios where you need to manage user sign-up, sign-in, and user profiles, consider using [Amazon Cognito](https://aws.amazon.com/cognito/) as an identity broker. For details about using Amazon Cognito with OIDC, see [Amazon Cognito for mobile apps](id_federation_common_scenarios.md#id_roles_providers_oidc_cognito).

**Note**  
JSON Web Tokens (JWTs) issued by OpenID Connect (OIDC) identity providers contain an expiration time in the `exp` claim that specifies when the token expires. IAM provides a five-minute window beyond the expiration time specified in the JWT to account for clock skew, as allowed by the [OpenID Connect (OIDC) Core 1.0 standard](https://openid.net/specs/openid-connect-core-1_0.html). This means OIDC JWTs received by IAM after the expiration time but within this five-minute window are accepted for further evaluation and processing.

**Topics**
+ [

## Additional resources for OIDC federation
](#id_roles_providers_oidc_resources)
+ [

# Create an OpenID Connect (OIDC) identity provider in IAM
](id_roles_providers_create_oidc.md)
+ [

# Obtain the thumbprint for an OpenID Connect identity provider
](id_roles_providers_create_oidc_verify-thumbprint.md)
+ [

# Identity-provider controls for shared OIDC providers
](id_roles_providers_oidc_secure-by-default.md)

## Additional resources for OIDC federation


The following resources can help you learn more about OIDC federation:
+ Use OpenID Connect within your GitHub workflows by [Configuring OpenID Connect in Amazon Web Services](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)
+ [Amazon Cognito Identity](https://docs.amplify.aws/lib/auth/advanced/q/platform/android/) in the *Amplify Libraries for Android Guide* and [Amazon Cognito Identity](https://docs.amplify.aws/lib/auth/advanced/q/platform/ios/) in the *Amplify Libraries for Swift Guide*.
+ [How to use external ID when granting access to your AWS resources](https://aws.amazon.com/blogs/security/how-to-use-external-id-when-granting-access-to-your-aws-resources/) on the *AWS Security Blog* provides guidance on securely configuring cross-account access and external identity federation.

# Create an OpenID Connect (OIDC) identity provider in IAM
Create OIDC identity provider

*IAM OIDC identity providers* are entities in IAM that describe an external identity provider (IdP) service that supports the [OpenID Connect](http://openid.net/connect/) (OIDC) standard, such as Google or Salesforce. You use an IAM OIDC identity provider when you want to establish trust between an OIDC-compatible IdP and your AWS account. This is useful when creating a mobile app or web application that requires access to AWS resources, but you don't want to create custom sign-in code or manage your own user identities. For more information about this scenario, see [OIDC federation](id_roles_providers_oidc.md).

You can create and manage an IAM OIDC identity provider using the AWS Management Console, the AWS Command Line Interface, the Tools for Windows PowerShell, or the IAM API.

After you create an IAM OIDC identity provider, you must create one or more IAM roles. A role is an identity in AWS that doesn't have its own credentials (as a user does). But in this context, a role is dynamically assigned to an OIDC federated principal that is authenticated by your organization's IdP. The role permits your organization's IdP to request temporary security credentials for access to AWS. The policies assigned to the role determine what users are allowed to do in AWS. To create a role for a third-party identity provider, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md).

**Important**  
When you configure identity-based policies for actions that support `oidc-provider` resources, IAM evaluates the full OIDC identity provider URL, including any specified paths. If your OIDC identity provider URL has a path, you must include that path in the `oidc-provider` ARN as a `Resource` element value. You also have the option to append a forward slash and wildcard (`/*`) to the URL domain or use wildcard characters (`*` and `?`) at any point in the URL path. If the OIDC identity provider URL in the request doesn't match the value set in the policy's `Resource` element, the request fails.

To troubleshoot common issues with IAM OIDC federation, see [Resolve errors related to OIDC](https://repost.aws/knowledge-center/iam-oidc-idp-federation) on AWS re:Post.

**Topics**
+ [

## Prerequisites: Validate configuration of your identity provider
](#manage-oidc-provider-prerequisites)
+ [

## Creating and managing an OIDC provider (console)
](#manage-oidc-provider-console)
+ [

## Creating and managing an IAM OIDC identity provider (AWS CLI)
](#manage-oidc-provider-cli)
+ [

## Creating and managing an OIDC Identity Provider (AWS API)
](#manage-oidc-provider-api)

## Prerequisites: Validate configuration of your identity provider
Prerequisites

Before you can create an IAM OIDC identity provider, you must have the following information from your IdP. For more information about obtaining OIDC provider configuration Information, see the documentation for your IdP.

1. Determine your OIDC identity provider’s publicly available URL. The URL must begin with https://. Per the OIDC standard, path components are allowed but query parameters are not. Typically, the URL consists of only a hostname, like https://server.example.org or https://example.com. The URL should not contain a port number.

1. Add **/.well-known/openid-configuration** to the end of your OIDC identity provider's URL to see the provider's publicly available configuration document and metadata. You must have a discovery document in JSON format with the provider's configuration document and metadata that can be retrieved from the [OpenID Connect provider discovery endpoint URL](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).

1. Confirm the following values are included in your provider’s configuration information. If your openid-configuration is missing any of these fields, you must update your discovery document. This process can vary based on your identity provider, so follow your IdP's documentation to complete this task.
   + issuer: The URL for your domain.
   + jwks\$1uri: The JSON Web Key Set (JWKS) endpoint where IAM gets your public keys. Your identity provider must include a JSON Web Key Set (JWKS) endpoint in the openid-configuration. This URI defines where to get your public keys that are used to verify the signed tokens from your identity provider.
**Note**  
The JSON Web Key Set (JWKS) must contain at least one key and can have a maximum of 100 RSA keys and 100 EC keys. If your OIDC identity provider's JWKS contains more than 100 RSA keys or 100 EC keys, an `InvalidIdentityToken` exception will be returned when using the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation with a JWT signed by a key type that exceeds the 100-key limit. For example, if a JWT is signed with the RSA algorithm and there are more than 100 RSA keys in your provider's JWKS, an `InvalidIdentityToken` exception will be returned.
   + claims\$1supported: Information about the user that helps you ensure OIDC authentication responses from your IdP contain the required attributes AWS uses in IAM policies to check permissions for OIDC federated principals. For a list of IAM condition keys that can be used for claims, see [Available keys for AWS OIDC federation](reference_policies_iam-condition-keys.md#condition-keys-wif).
     + aud: You must determine the audience claim value your IdP issues in JSON Web Tokens (JWTs). The audience (aud) claim is application specific and identifies the intended recipients of the token. When you register a mobile or web app with an OpenID Connect provider, they establish a client ID that identifies the application. The client ID is a unique identifier for your app that is passed in the aud claim for authentication. The aud claim must match the Audience value when creating your IAM OIDC identity provider.
     + iat: Claims must include a value for `iat` that represents the time that the ID token is issued.
     + iss: The URL of the identity provider. The URL must begin with https:// and should correspond to the Provider URL provided to IAM. Per the OIDC standard, path components are allowed but query parameters are not. Typically, the URL consists of only a hostname, like https://server.example.org or https://example.com. The URL should not contain a port number.
   + response\$1types\$1supported: id\$1token
   + subject\$1types\$1supported: public
   + id\$1token\$1signing\$1alg\$1values\$1supported: RS256, RS384, RS512, ES256, ES384, ES512
**Note**  
You can include additional claims like `my_custom_claim` in the example below; however, AWS STS will ignore the claim.  

   ```
   {
     "issuer": "https://example-domain.com",
     "jwks_uri": "https://example-domain.com/jwks/keys",
     "claims_supported": [
       "aud",
       "iat",
       "iss",
       "name",
       "sub",
       "my_custom_claim"
     ],
     "response_types_supported": [
       "id_token"
     ],
     "id_token_signing_alg_values_supported": [
       "RS256",
       "RS384",
       "RS512",
       "ES256",
       "ES384",
       "ES512"
     ],
     "subject_types_supported": [
       "public"
     ]
   }
   ```

## Creating and managing an OIDC provider (console)


Follow these instructions to create and manage an IAM OIDC identity provider in the AWS Management Console.

**Important**  
If you are using an OIDC identity provider from either Google, Facebook, or Amazon Cognito, do not create a separate IAM identity provider using this procedure. These OIDC identity providers are already built-in to AWS and are available for your use. Instead, follow the steps to create new roles for your identity provider, see [Create a role for OpenID Connect federation (console)](id_roles_create_for-idp_oidc.md).

**To create an IAM OIDC identity provider (console)**

1. <a name="idpoidcstep1"></a>Before you create an IAM OIDC identity provider, you must register your application with the IdP to receive a *client ID*. The client ID (also known as *audience*) is a unique identifier for your app that is issued to you when you register your app with the IdP. For more information about obtaining a client ID, see the documentation for your IdP. 
**Note**  
AWS secures communication with OIDC identity providers (IdPs) using our library of trusted root certificate authorities (CAs) to verify the JSON Web Key Set (JWKS) endpoint's TLS certificate. If your OIDC IdP relies on a certificate that is not signed by one of these trusted CAs, only then we secure communication using the thumbprints set in the IdP's configuration. AWS will fall back to thumbprint verification if we are unable to retrieve the TLS certificate or if TLS v1.3 is required.

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Identity providers**, and then choose **Add provider**.

1. For **Configure provider**, choose **OpenID Connect**. 

1. For **Provider URL**, type the URL of the IdP. The URL must comply with these restrictions:
   + The URL is case-sensitive.
   + The URL must begin with **https://**.
   + The URL should not contain a port number. 
   + Within your AWS account, each IAM OIDC identity provider must use a unique URL. If you try to submit a URL that has already been used for an OpenID Connect provider in the AWS account, you will get an error.

1. For **Audience**, type the client ID of the application that you registered with the IdP and received in [Step 1](#idpoidcstep1), and that make requests to AWS. If you have additional client IDs (also known as *audiences*) for this IdP, you can add them later on the provider detail page.
**Note**  
If your IdP JWT token includes the `azp` claim, enter this value as the Audience value.  
If your OIDC identity provider is setting both `aud` and `azp` claims in the token, AWS STS will use the value in the `azp` claim as the `aud` claim.

1. (Optional) For **Add tags**, you can add key–value pairs to help you identify and organize your IdPs. You can also use tags to control access to AWS resources. To learn more about tagging IAM OIDC identity providers, see [Tag OpenID Connect (OIDC) identity providers](id_tags_oidc.md). Choose **Add tag**. Enter values for each tag key-value pair. 

1. Verify the information that you have provided. When you are done choose **Add provider**. IAM will attempt to retrieve and use the top intermediate CA thumbprint of the OIDC IdP server certificate to create the IAM OIDC identity provider.
**Note**  
The OIDC identity provider's certificate chain must start with the domain or issuer URL, then the intermediate certificate, and end with the root certificate. If the certificate chain order is different or includes duplicate or additional certificates, then you receive a signature mismatch error and STS fails to validate the JSON Web Token (JWT). Correct the order of the certificates in the chain returned from the server to resolve the error. For more information about certificate chain standards, see [certificate\$1list in RFC 5246](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.2) on the RFC Series website.

1. Assign an IAM role to your identity provider to give external user identities managed by your identity provider permissions to access AWS resources in your account. To learn more about creating roles for identity federation, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md).
**Note**  
OIDC IdPs used in a role trust policy must be in the same account as the role that trusts it.

**To add or remove a thumbprint for an IAM OIDC identity provider (console)**
**Note**  
AWS secures communication with OIDC identity providers (IdPs) using our library of trusted root certificate authorities (CAs) to verify the JSON Web Key Set (JWKS) endpoint's TLS certificate. If your OIDC IdP relies on a certificate that is not signed by one of these trusted CAs, only then we secure communication using the thumbprints set in the IdP's configuration. AWS will fall back to thumbprint verification if we are unable to retrieve the TLS certificate or if TLS v1.3 is required.

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Identity providers**. Then choose the name of the IAM identity provider that you want to update.

1. Choose the **Endpoint verification** tab, then in the **Thumbprints** section, choose **Manage**. To enter a new thumbprint value, choose **Add thumbprint**. To remove a thumbprint, choose **Remove** next to the thumbprint that you want to remove.
**Note**  
An IAM OIDC identity provider must have at least one and can have a maximum of five thumbprints.

    When you are done, choose **Save changes**.

**To add an audience for an IAM OIDC identity provider (console)**

1. In the navigation pane, choose **Identity providers**, then choose the name of the IAM identity provider that you want to update.

1. In the **Audiences** section, choose **Actions** and select **Add audience**. 

1. Type the client ID of the application that you registered with the IdP and received in [Step 1](#idpoidcstep1), and that will make requests to AWS. Then choose **Add audiences**.
**Note**  
An IAM OIDC identity provider must have at least one and can have a maximum of 100 audiences.

**To remove an audience for an IAM OIDC identity provider (console)**

1. In the navigation pane, choose **Identity providers**, then choose the name of the IAM identity provider that you want to update.

1. In the **Audiences** section, select the radio button next to the audience that you want to remove, then select **Actions**.

1.  Choose **Remove audience**. A new window opens.

1. If you remove an audience, identities federating with the audience cannot assume roles associated with the audience. In the window, read the warning and confirm that you want to remove the audience by typing the word `remove` in the field.

1. Choose **Remove** to remove the audience.

**To delete an IAM OIDC identity provider (console)**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Identity providers**. 

1. Select the checkbox next to the IAM identity provider that you want to delete. A new window opens.

1. Confirm that you want to delete the provider by typing the word `delete` in the field. Then, choose **Delete**.

## Creating and managing an IAM OIDC identity provider (AWS CLI)


You can use the following AWS CLI commands to create and manage IAM OIDC identity providers.

**To create an IAM OIDC identity provider (AWS CLI)**

1. (Optional) To get a list of all the IAM OIDC identity providers in your AWS account, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html)

1. To create a new IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/create-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-open-id-connect-provider.html)

**To update the list of server certificate thumbprints for an existing IAM OIDC identity provider (AWS CLI)**
+ To update the list of server certificate thumbprints for an IAM OIDC identity provider, run the following command:
  + [https://docs.aws.amazon.com/cli/latest/reference/iam/update-open-id-connect-provider-thumbprint.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-open-id-connect-provider-thumbprint.html)

**To tag an existing IAM OIDC identity provider (AWS CLI)**
+ To tag an existing IAM OIDC identity provider, run the following command:
  + [https://docs.aws.amazon.com/cli/latest/reference/iam/tag-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-open-id-connect-provider.html)

**To list tags for an existing IAM OIDC identity provider (AWS CLI)**
+ To list tags for an existing IAM OIDC identity provider, run the following command:
  + [https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-provider-tags.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-provider-tags.html)

**To remove tags on an IAM OIDC identity provider (AWS CLI)**
+ To remove tags on an existing IAM OIDC identity provider, run the following command:
  + [https://docs.aws.amazon.com/cli/latest/reference/iam/untag-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-open-id-connect-provider.html)

**To add or remove a client ID from an existing IAM OIDC identity provider (AWS CLI)**

1. (Optional) To get a list of all the IAM OIDC identity provider in your AWS account, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html)

1. (Optional) To get detailed information about an IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/get-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-open-id-connect-provider.html)

1. To add a new client ID to an existing IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/add-client-id-to-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/add-client-id-to-open-id-connect-provider.html)

1. To remove a client from an existing IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/remove-client-id-from-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-client-id-from-open-id-connect-provider.html)

**To delete an IAM OIDC identity provider (AWS CLI)**

1. (Optional) To get a list of all the IAM OIDC identity provider in your AWS account, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html)

1. (Optional) To get detailed information about an IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/get-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-open-id-connect-provider.html)

1. To delete an IAM OIDC identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-open-id-connect-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-open-id-connect-provider.html)

## Creating and managing an OIDC Identity Provider (AWS API)


You can use the following IAM API commands to create and manage OIDC providers.

**To create an IAM OIDC identity provider (AWS API)**

1. (Optional) To get a list of all the IAM OIDC identity provider in your AWS account, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html)

1. To create a new IAM OIDC identity provider, call the following operation: 
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateOpenIDConnectProvider.html)

**To update the list of server certificate thumbprints for an existing IAM OIDC identity provider (AWS API)**
+ To update the list of server certificate thumbprints for an IAM OIDC identity provider, call the following operation:
  + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateOpenIDConnectProviderThumbprint.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateOpenIDConnectProviderThumbprint.html)

**To tag an existing IAM OIDC identity provider (AWS API)**
+ To tag an existing IAM OIDC identity provider, call the following operation:
  + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagOpenIDConnectProvider.html)

**To list tags for an existing IAM OIDC identity provider (AWS API)**
+ To list tags for an existing IAM OIDC identity provider, call the following operation:
  + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviderTags.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviderTags.html)

**To remove tags on an existing IAM OIDC identity provider (AWS API)**
+ To remove tags on an existing IAM OIDC identity provider, call the following operation:
  + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagOpenIDConnectProvider.html)

**To add or remove a client ID from an existing IAM OIDC identity provider (AWS API)**

1. (Optional) To get a list of all the IAM OIDC identity provider in your AWS account, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html)

1. (Optional) To get detailed information about an IAM OIDC identity provider, call the following operation: 
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOpenIDConnectProvider.html)

1. To add a new client ID to an existing IAM OIDC identity provider, call the following operation: 
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddClientIDToOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddClientIDToOpenIDConnectProvider.html)

1. To remove a client ID from an existing IAM OIDC identity provider, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveClientIDFromOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveClientIDFromOpenIDConnectProvider.html)

**To delete an IAM OIDC identity provider (AWS API)**

1. (Optional) To get a list of all the IAM OIDC identity provider in your AWS account, call the following operation: 
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html)

1. (Optional) To get detailed information about an IAM OIDC identity provider, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOpenIDConnectProvider.html)

1. To delete an IAM OIDC identity provider, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteOpenIDConnectProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteOpenIDConnectProvider.html)

# Obtain the thumbprint for an OpenID Connect identity provider
Obtain the thumbprint for an OIDC provider

When you [create an OpenID Connect (OIDC) identity provider](id_roles_providers_create_oidc.md) in IAM, IAM requires the thumbprint for the top intermediate certificate authority (CA) that signed the certificate used by the external identity provider (IdP). The thumbprint is a signature for the CA's certificate that was used to issue the certificate for the OIDC-compatible IdP. When you create an IAM OIDC identity provider, you are trusting identities authenticated by that IdP to have access to your AWS account. By using the CA's certificate thumbprint, you trust any certificate issued by that CA with the same DNS name as the one registered. This eliminates the need to update trusts in each account when you renew the IdP's signing certificate.

**Important**  
In most cases, the federation server uses two different certificates:  
The first establishes an HTTPS connection between AWS and your IdP. This should be issued by a well-known public root CA, such as AWS Certificate Manager. This enables the client to check the reliability and status of the certificate.
The second is used to encrypt tokens, and should be signed by a private or public *root* CA.

You can create an IAM OIDC identity provider with [the AWS Command Line Interface, the Tools for Windows PowerShell, or the IAM API](id_roles_providers_create_oidc.md#manage-oidc-provider-cli). When you use these methods, you have the option to manually provide a thumbprint. If you choose not to include a thumbprint, IAM will retrieve the top intermediate CA thumbprint of the OIDC IdP server certificate. If you choose to include a thumbprint, you must obtain the thumbprint manually and supply it to AWS.

When you create an OIDC identity provider with [the IAM console](id_roles_providers_create_oidc.md), IAM attempts to retrieve the top intermediate CA thumbprint of the OIDC IdP server certificate for you. 

We recommend that you also obtain the thumbprint for your OIDC IdP manually and verify that IAM retrieved the correct thumbprint. For more information about obtaining certificate thumbprints, see the following sections.

**Note**  
AWS secures communication with OIDC identity providers (IdPs) using our library of trusted root certificate authorities (CAs) to verify the JSON Web Key Set (JWKS) endpoint's TLS certificate. If your OIDC IdP relies on a certificate that is not signed by one of these trusted CAs, only then we secure communication using the thumbprints set in the IdP's configuration. AWS will fall back to thumbprint verification if we are unable to retrieve the TLS certificate or if TLS v1.3 is required.

## Obtain certificate thumbprint


You use a web browser and the OpenSSL command line tool to obtain the certificate thumbprint for an OIDC provider. However, you do not need to manually obtain the certificate thumbprint to create an IAM OIDC identity provider. You can use the following procedure to obtain the certificate thumbprint of your OIDC provider.

**To obtain the thumbprint for an OIDC IdP**

1. Before you can obtain the thumbprint for an OIDC IdP, you need to obtain the OpenSSL command line tool. You use this tool to download the OIDC IdP certificate chain and produce a thumbprint of the final certificate in the certificate chain. If you need to install and configure OpenSSL, follow the instructions at [Install OpenSSL](#oidc-install-openssl) and [Configure OpenSSL](#oidc-configure-openssl).

1. Start with the OIDC IdP URL (for example, `https://server.example.com`), and then add `/.well-known/openid-configuration` to form the URL for the IdP's configuration document, such as the following:

   **https://*server.example.com*/.well-known/openid-configuration**

   Open this URL in a web browser, replacing *server.example.com* with your IdP server name. 

1. <a name="thumbstep2"></a>In the displayed document, use your web browser **Find** feature to locate the text `"jwks_uri"`. Immediately following the text `"jwks_uri"`, there is a colon (:) followed by a URL. Copy the fully qualified domain name of the URL. Do not include `https://` or any path that comes after the top-level domain. 

   ```
   {
    "issuer": "https://accounts.example.com",
    "authorization_endpoint": "https://accounts.example.com/o/oauth2/v2/auth",
    "device_authorization_endpoint": "https://oauth2.exampleapis.com/device/code",
    "token_endpoint": "https://oauth2.exampleapis.com/token",
    "userinfo_endpoint": "https://openidconnect.exampleapis.com/v1/userinfo",
    "revocation_endpoint": "https://oauth2.exampleapis.com/revoke",
    "jwks_uri": "https://www.exampleapis.com/oauth2/v3/certs",
   ...
   ```

1. Use the OpenSSL command line tool to run the following command. Replace *keys.example.com* with the domain name you obtained in [Step 3](#thumbstep2).

   ```
   openssl s_client -servername keys.example.com -showcerts -connect keys.example.com:443
   ```

1. In your command window, scroll up until you see a certificate similar to the following example. If you see more than one certificate, find the last certificate displayed (at the end of the command output). This contains the certificate of the top intermediate CA in the certificate authority chain.

   ```
   -----BEGIN CERTIFICATE-----
    MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
    -----END CERTIFICATE-----
   ```

   Copy the certificate (including the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines) and paste it into a text file. Then save the file with the file name **certificate.crt**.
**Note**  
The OIDC identity provider's certificate chain must start with the domain or issuer URL, include any intermediate certificates (if present), and end with the root certificate. If the certificate chain order is different or includes duplicate or additional certificates, you will receive a signature mismatch error and STS fails to validate the JSON Web Token (JWT). Correct the order of the certificates in the chain returned from the server to resolve the error. For more information about certificate chain standards, see [certificate\$1list in RFC 5246](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.2) on the RFC Series website.

1. Use the OpenSSL command line tool to run the following command.

   ```
   openssl x509 -in certificate.crt -fingerprint -sha1 -noout
   ```

   Your command window displays the certificate thumbprint, which looks similar to the following example:

   ```
   SHA1 Fingerprint=99:0F:41:93:97:2F:2B:EC:F1:2D:DE:DA:52:37:F9:C9:52:F2:0D:9E
   ```

   Remove the colon characters (:) from this string to produce the final thumbprint, like this:

   ```
   990F4193972F2BECF12DDEDA5237F9C952F20D9E
   ```

1. If you are creating the IAM OIDC identity provider with the AWS CLI, Tools for Windows PowerShell, or the IAM API, providing a thumbprint is optional. If you choose not to include a thumbprint during creation, IAM will retrieve the top intermediate CA thumbprint of the OIDC IdP server certificate. After the IAM OIDC identity provider is created, you can compare this thumbprint to the thumbprint retrieved by IAM.

   If you are creating the IAM OIDC identity provider in the IAM console, the console attempts to retrieve the top intermediate CA thumbprint of the OIDC IdP server certificate for you. You can compare this thumbprint to the thumbprint retrieved by IAM. After the IAM OIDC identity provider is created, you can view the thumbprint for the IAM OIDC identity provider in the **Endpoint verification** tab on the OIDC provider **Summary** console page.
**Important**  
If the thumbprint you obtained does not match the one you see in the IAM OIDC identity provider thumbprint details, you should not use the OIDC provider. Instead, you should delete the created OIDC provider and then try again to create the OIDC provider after some time has passed. Verify that the thumbprints match before you use the provider. If the thumbprints still do not match after a second attempt, use the [IAM Forum](https://forums.aws.amazon.com/forum.jspa?forumID=76) to contact AWS.

## Install OpenSSL


If you don't already have OpenSSL installed, follow the instructions in this section.

**To install OpenSSL on Linux or Unix**

1. Go to [OpenSSL: Source, Tarballs](https://openssl.org/source/) (https://openssl.org/source/).

1. Download the latest source and build the package.

**To install OpenSSL on Windows**

1. Go to [OpenSSL: Binary Distributions](https://wiki.openssl.org/index.php/Binaries) (https://wiki.openssl.org/index.php/Binaries) for a list of sites from which you can install the Windows version.

1. Follow the instructions on your selected site to start the installation.

1. If you are asked to install the **Microsoft Visual C\$1\$1 2008 Redistributables ** and it is not already installed on your system, choose the download link appropriate for your environment. Follow the instructions provided by the **Microsoft Visual C\$1\$1 2008 Redistributable Setup Wizard**.
**Note**  
If you are not sure whether the Microsoft Visual C\$1\$1 2008 Redistributables is already installed on your system, you can try installing OpenSSL first. The OpenSSL installer displays an alert if the Microsoft Visual C\$1\$1 2008 Redistributables is not yet installed. Make sure that you install the architecture (32-bit or 64-bit) that matches the version of OpenSSL that you install.

1. After you have installed the Microsoft Visual C\$1\$1 2008 Redistributables, select the appropriate version of the OpenSSL binaries for your environment and save the file locally. Start the **OpenSSL Setup Wizard**.

1. Follow the instructions described in the **OpenSSL Setup Wizard**.

## Configure OpenSSL


Before you use OpenSSL commands, you must configure the operating system so that it has information about the location where OpenSSL is installed.

**To configure OpenSSL on Linux or Unix**

1. At the command line, set the `OpenSSL_HOME` variable to the location of the OpenSSL installation:

   ```
   $ export OpenSSL_HOME=path_to_your_OpenSSL_installation
   ```

1. Set the path to include the OpenSSL installation:

   ```
   $ export PATH=$PATH:$OpenSSL_HOME/bin
   ```
**Note**  
Any changes you make to environment variables with the `export` command are valid only for the current session. You can make persistent changes to the environment variables by setting them in your shell configuration file. For more information, see the documentation for your operating system.

**To configure OpenSSL on Windows**

1. Open a **Command Prompt** window.

1. Set the `OpenSSL_HOME` variable to the location of the OpenSSL installation:

   ```
   C:\> set OpenSSL_HOME=path_to_your_OpenSSL_installation
   ```

1. Set the `OpenSSL_CONF` variable to the location of the configuration file in your OpenSSL installation:

   ```
   C:\> set OpenSSL_CONF=path_to_your_OpenSSL_installation\bin\openssl.cfg
   ```

1. Set the path to include the OpenSSL installation:

   ```
   C:\> set Path=%Path%;%OpenSSL_HOME%\bin
   ```
**Note**  
Any changes you make to Windows environment variables in a **Command Prompt** window are valid only for the current command line session. You can make persistent changes to the environment variables by setting them as system properties. The exact procedures depend on what version of Windows you're using. (For example, in Windows 7, open **Control Panel**, **System and Security**, **System**. Then choose **Advanced system settings**, **Advanced** tab, **Environment Variables**.) For more information, see the Windows documentation.

# Identity-provider controls for shared OIDC providers
Identity-provider controls for shared OIDC providers

For recognized shared OpenID Connect (OIDC) identity providers (IdPs), IAM requires explicit evaluation of specific claims in role trust policies. These required claims, called *identity-provider controls*, are evaluated by IAM during role creation and trust policy updates. If the role trust policy does not evaluate the controls required by the shared OIDC IdP, the role creation or update would fail. This ensures that only authorized identities from the intended organization can assume roles and access AWS resources. This security control is crucial when OIDC providers are shared across multiple AWS customers.



Identity-provider controls will not be evaluated by IAM for existing OIDC role trust policies. For any modifications to the role trust policy for existing OIDC roles, IAM will require that identity-provider controls be included in the role trust policy.

## OIDC provider types


IAM categorizes OIDC identity providers into two distinct types: **private** and **shared**. A private OIDC IdP can be owned and managed by a single organization or can be a tenant of a SaaS provider, with its OIDC Issuer URL serving as a unique identifier specific to that organization. In contrast, a shared OIDC IdP is utilized across multiple organizations, where the OIDC Issuer URL might be identical for all organizations using that shared identity provider.

The table below outlines the key differences between private and shared OIDC providers:


| Characteristic | Private OIDC Provider | Shared OIDC Provider | 
| --- | --- | --- | 
|  Issuer  |  Unique to the organization  |  Shared across multiple organizations  | 
|  Tenancy Information  |  Communicated through unique Issuer  |  Communicated through claims in JWT  | 
|  Trust Policy Requirements  |  No specific claim evaluation required  |  Evaluation of specific claims required  | 

## Shared OIDC identity providers with identity-provider controls


When you create or modify an OIDC provider in IAM, the system automatically identifies and evaluates required claims for recognized shared OIDC providers. If identity-provider controls are not configured in the role trust policy, the role creation or update will fail with a MalformedPolicyDocument error.

The following table lists the shared OIDC providers that require identity-provider controls in role trust policies and additional information to help you configure identity-provider controls.


| OIDC IdP | OIDC URL | Tenancy Claim | Required Claims | 
| --- | --- | --- | --- | 
| [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html) |  `cognito-identity.amazonaws.com`  | aud |  `cognito-identity.amazonaws.com:aud`  | 
| [Azure Sentinel](https://learn.microsoft.com/en-us/azure/defender-for-cloud/sentinel-connected-aws) |  https://sts.windows.net/33e01921-4d64-4f8c-a055-5bdaffd5e33d  |  sts:RoleSessionName  |  sts:RoleSessionName  | 
| [Buildkite](https://buildkite.com/docs/pipelines/security/oidc/aws) |  https://agent.buildkite.com  |  sub  |  agent.buildkite.com:sub  | 
| [Codefresh SaaS](https://codefresh.io/docs/docs/integrations/oidc-pipelines/) | https://oidc.codefresh.io | sub |  oidc.codefresh.io:sub  | 
| [DVC Studio](https://dvc.org/doc/studio/user-guide/openid-connect) | https://studio.datachain.ai/api | sub |  studio.datachain.ai/api:sub  | 
| [GitHub actions](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services) | https://token.actions.githubusercontent.com | sub |  token.actions.githubusercontent.com:sub  | 
| [GitHub audit log streaming](https://docs.github.com/en/enterprise-cloud@latest/admin/monitoring-activity-in-your-enterprise/reviewing-audit-logs-for-your-enterprise/streaming-the-audit-log-for-your-enterprise) | https://oidc-configuration.audit-log.githubusercontent.com | sub |  oidc-configuration.audit-log.githubusercontent.com:sub  | 
| [GitHub vstoken](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services) | https://vstoken.actions.githubusercontent.com | sub |  vstoken.actions.githubusercontent.com:sub  | 
| [GitLab](https://docs.gitlab.com/ci/cloud_services/aws/) | https://gitlab.com | sub |  gitlab.com:sub  | 
| [IBM Turbonomic SaaS\$1](https://www.ibm.com/docs/en/tarm/8.16.x?topic=turbonomic-setting-up-aws-iam-role-saas-deployments) |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_secure-by-default.html)  | sub |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_secure-by-default.html)  | 
| [Pulumi Cloud](https://www.pulumi.com/docs/pulumi-cloud/deployments/oidc/aws/) | https://api.pulumi.com/oidc | aud |  api.pulumi.com/oidc:aud  | 
| [sandboxes.cloud](https://docs.sandboxes.cloud/docs/cloud-resources-setup) | https://sandboxes.cloud | aud |  sandboxes.cloud:aud  | 
| [Scalr](https://docs.scalr.io/docs/aws) | https://scalr.io | sub |  scalr.io:sub  | 
| [Shisho Cloud](https://shisho.dev/docs/g/getting-started/integrate-apps/aws/) | https://tokens.cloud.shisho.dev | sub |  tokens.cloud.shisho.dev:sub  | 
| [Terraform Cloud](https://developer.hashicorp.com/terraform/cloud-docs/workspaces/dynamic-provider-credentials/aws-configuration) | https://app.terraform.io | sub |  app.terraform.io:sub  | 
| [Upbound](https://docs.upbound.io/providers/provider-aws/authentication/) | https://proidc.upbound.io | sub |  proidc.upbound.io:sub  | 
| [Vercel global endpoint](https://vercel.com/docs/oidc/reference) | https://oidc.vercel.com | aud |  oidc.vercel.com:aud  | 

\$1 IBM Turbonomic periodically updates their OIDC Issuer URL with new versions of the platform. We will add additional Turbonomic OIDC issuers in scope as a shared provider as needed.

For any new OIDC IdPs that IAM identifies as shared, the required identity-provider controls for role trust policies will be documented and enforced in a similar manner.

## Additional resources


Additional resources:
+ For more information about creating an IAM role for OIDC federation, see [Create a role for OpenID Connect federation (console)](id_roles_create_for-idp_oidc.md).
+ For a list of IAM condition keys that can be used for claims, see [Available keys for AWS OIDC federation](reference_policies_iam-condition-keys.md#condition-keys-wif).

# SAML 2.0 federation


AWS supports identity federation with [SAML 2.0 (Security Assertion Markup Language 2.0)](https://wiki.oasis-open.org/security), an open standard that many identity providers (IdPs) use. This feature enables federated single sign-on (SSO), so users can log into the AWS Management Console or call AWS API operations without you having to create an IAM user for everyone in your organization. By using SAML, you can simplify the process of configuring federation with AWS, because you can use the IdP's service instead of [writing custom identity proxy code](https://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingFedTokens.html).

**Note**  
IAM SAML identity federation supports encrypted SAML responses from SAML-based federated identity providers (IdPs). IAM Identity Center and Amazon Cognito do not support encrypted SAML assertions from IAM SAML identity providers.  
You can indirectly add support for encrypted SAML assertions to Amazon Cognito identity pool federation with Amazon Cognito user pools. User pools have SAML federation that's independent of IAM SAML federation and supports [SAML signing and encryption](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-SAML-signing-encryption.html). Although this feature doesn't extend directly to identity pools, user pools can be IdPs to identity pools. To use SAML encryption with identity pools, add a SAML provider with encryption to a user pool that is an IdP to an identity pool.  
Your SAML provider must be able to encrypt SAML assertions with a key that your user pool provides. User pools won't accept assertions encrypted with a certificate that IAM has provided.

IAM federation supports these use cases: 
+ [**Federated access to allow a user or application in your organization to call AWS API operations**](#CreatingSAML-configuring). This use case is discussed in the following section. You use a SAML assertion (as part of the authentication response) that is generated in your organization to get temporary security credentials. This scenario is similar to other federation scenarios that IAM supports, like those described in [Request temporary security credentials](id_credentials_temp_request.md) and [OIDC federation](id_roles_providers_oidc.md). However, SAML 2.0–based IdPs in your organization handle many of the details at run time for performing authentication and authorization checking.
+ [**Web-based single sign-on (SSO) to the AWS Management Console from your organization**](id_roles_providers_enable-console-saml.md). Users can sign in to a portal in your organization hosted by a SAML 2.0–compatible IdP, select an option to go to AWS, and be redirected to the console without having to provide additional sign-in information. You can use a third-party SAML IdP to establish SSO access to the console or you can create a custom IdP to enable console access for your external users. For more information about building a custom IdP, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).

**Topics**
+ [

## Using SAML-based federation for API access to AWS
](#CreatingSAML-configuring)
+ [

## Overview of configuring SAML 2.0-based federation
](#CreatingSAML-configuring-IdP)
+ [

## Overview of the role to allow SAML-federated access to your AWS resources
](#CreatingSAML-configuring-role)
+ [

## Uniquely identifying users in SAML-based federation
](#CreatingSAML-userid)
+ [

# Create a SAML identity provider in IAM
](id_roles_providers_create_saml.md)
+ [

# Configure your SAML 2.0 IdP with relying party trust and adding claims
](id_roles_providers_create_saml_relying-party.md)
+ [

# Integrate third-party SAML solution providers with AWS
](id_roles_providers_saml_3rd-party.md)
+ [

# Configure SAML assertions for the authentication response
](id_roles_providers_create_saml_assertions.md)
+ [

# Enabling SAML 2.0 federated principals to access the AWS Management Console
](id_roles_providers_enable-console-saml.md)
+ [

# View a SAML response in your browser
](troubleshoot_saml_view-saml-response.md)

## Using SAML-based federation for API access to AWS


Assume that you want to provide a way for employees to copy data from their computers to a backup folder. You build an application that users can run on their computers. On the back end, the application reads and writes objects in an Amazon S3 bucket. Users don't have direct access to AWS. Instead, the following process is used:

![\[Getting temporary security credentials based on a SAML assertion\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/saml-based-federation-diagram.png)


1. A user in your organization uses a client app to request authentication from your organization's IdP.

1. The IdP authenticates the user against your organization's identity store.

1. The IdP constructs a SAML assertion with information about the user and sends the assertion to the client app. When you enable SAML encryption for your IAM SAML IdP, this assertion is encrypted by your external IdP.

1. The client app calls the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API, passing the ARN of the SAML provider, the ARN of the role to assume, and the SAML assertion from IdP. If encryption is enabled, the assertion passed through the client app remains encrypted in transit.

1. (Optional) AWS STS uses the private key you uploaded from your external IdP to decrypt the encrypted SAML assertion.

1. The API response to the client app includes temporary security credentials.

1. The client app uses the temporary security credentials to call Amazon S3 API operations. 

## Overview of configuring SAML 2.0-based federation


Before you can use SAML 2.0-based federation as described in the preceding scenario and diagram, you must configure your organization's IdP and your AWS account to trust each other. The general process for configuring this trust is described in the following steps. Inside your organization, you must have an [IdP that supports SAML 2.0](id_roles_providers_saml_3rd-party.md), like Microsoft Active Directory Federation Service (AD FS, part of Windows Server), Shibboleth, or another compatible SAML 2.0 provider. 

**Note**  
To improve federation resiliency, we recommend that you configure your IdP and AWS federation to support multiple SAML sign-in endpoints. For details, see the AWS Security Blog article [How to use regional SAML endpoints for failover](https://aws.amazon.com/blogs//security/how-to-use-regional-saml-endpoints-for-failover).

**Configure your organization's IdP and AWS to trust each other**

1. Register AWS as a service provider (SP) with the IdP of your organization. Use the SAML metadata document from `https://region-code.signin.aws.amazon.com/static/saml-metadata.xml` 

   For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html).

   You can optionally use the SAML metadata document from `https://signin.aws.amazon.com/static/saml-metadata.xml` .

1. <a name="createxml"></a>Using your organization's IdP, you generate an equivalent SAML metadata XML file that can describe your IdP as an IAM identity provider in AWS. It must include the issuer name, a creation date, an expiration date, and keys that AWS can use to validate authentication responses (assertions) from your organization. 

   If you allow encrypted SAML assertions to be sent from your external IdP, you must generate a private key file using your organization's IdP, and upload this file to your IAM SAML configuration in .pem file format. AWS STS needs this private key to decrypt SAML responses that correspond to the public key uploaded to your IdP.
**Note**  
As defined by the [SAML V2.0 Metadata Interoperability Profile Version 1.0](https://docs.oasis-open.org/security/saml/Post2.0/sstc-metadata-iop-os.html), IAM does not evaluate or take action on the expiration of X.509 certificates in SAML metadata documents. If you are concerned about expired X.509 certificates, we recommend monitoring certificate expiration dates and rotating certificates according to your organization’s governance and security policies.

1. <a name="samlovrcreateentity"></a>In the IAM console, you create a SAML identity provider. As part of this process, you upload the SAML metadata document and private decryption key that was produced by the IdP in your organization in [Step 2](#createxml). For more information, see [Create a SAML identity provider in IAM](id_roles_providers_create_saml.md).

1. <a name="samlovrcreaterole"></a>In IAM, you create one or more IAM roles. In the role's trust policy, you set the SAML provider as the principal, which establishes a trust relationship between your organization and AWS. The role's permission policy establishes what users from your organization are allowed to do in AWS. For more information, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md).
**Note**  
SAML IDPs used in a role trust policy must be in the same account that the role is in.

1. In your organization's IdP, you define assertions that map users or groups in your organization to the IAM roles. Note that different users and groups in your organization might map to different IAM roles. The exact steps for performing the mapping depend on what IdP you're using. In the [earlier scenario](#CreatingSAML-configuring) of an Amazon S3 folder for users, it's possible that all users will map to the same role that provides Amazon S3 permissions. For more information, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md).

   If your IdP enables SSO to the AWS console, then you can configure the maximum duration of the console sessions. For more information, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md).

1. In the application that you're creating, you call the AWS Security Token Service `AssumeRoleWithSAML` API, passing it the ARN of the SAML provider you created in [Step 3](#samlovrcreateentity), the ARN of the role to assume that you created in [Step 4](#samlovrcreaterole), and the SAML assertion about the current user that you get from your IdP. AWS makes sure that the request to assume the role comes from the IdP referenced in the SAML provider. 

   For more information, see [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) in the *AWS Security Token Service API Reference*. 

1. If the request is successful, the API returns a set of temporary security credentials, which your application can use to make signed requests to AWS. Your application has information about the current user and can access user-specific folders in Amazon S3, as described in the previous scenario. 

## Overview of the role to allow SAML-federated access to your AWS resources


The roles that you create in IAM define what SAML federated principals from your organization are allowed to do in AWS. When you create the trust policy for the role, you specify the SAML provider that you created earlier as the `Principal`. You can additionally scope the trust policy with a `Condition` to allow only users that match certain SAML attributes to access the role. For example, you can specify that only users whose SAML affiliation is `staff` (as asserted by https://openidp.feide.no) are allowed to access the role, as illustrated by the following sample policy:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::111122223333:saml-provider/ExampleOrgSSOProvider"},
    "Action": "sts:AssumeRoleWithSAML",
    "Condition": {
      "StringEquals": {
        "saml:aud": "https://us-east-1.signin.aws.amazon.com/saml",
        "saml:iss": "https://openidp.feide.no"
      },
      "ForAllValues:StringLike": {"saml:edupersonaffiliation": ["staff"]}
    }
  }]
}
```

------

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws-cn:iam::111122223333:saml-provider/ExampleOrgSSOProvider"
            },
            "Action": "sts:AssumeRoleWithSAML",
            "Condition": {
                "StringEquals": {
                    "saml:aud": "https://ap-east-1.signin.amazonaws.cn/saml",
                    "saml:iss": "https://openidp.feide.no"
                },
                "ForAllValues:StringLike": {
                    "saml:edupersonaffiliation": [
                        "staff"
                    ]
                }
            }
        }
    ]
}
```

------

**Note**  
SAML IDPs used in a role trust policy must be in the same account that the role is in.

The `saml:aud` context key in the policy specifies the URL your browser displays when signing into the console. This sign-in endpoint URL must match your identity provider's recipient attribute. You can include sign-in URLs within particular regions. AWS recommends using Regional endpoints instead of the global endpoint to improve federation resiliency. If you have only one endpoint configured, you won’t be able to federate into AWS in the unlikely event that the endpoint becomes unavailable. For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html).

The following example shows the sign-in URL format with the optional `region-code`.

`https://region-code.signin.aws.amazon.com/saml`

If SAML encryption is required, the sign-in URL must include the unique identifier AWS assigns to your SAML provider, which you can find on the Identity provider detail page. In the following example, the sign-in URL includes the IdP unique identifier, which requires /acs/ be appended to the sign-in path.

`https://region-code.signin.aws.amazon.com/saml/acs/IdP-ID`

For the permission policy in the role, you specify permissions as you would for any role. For example, if users from your organization are allowed to administer Amazon Elastic Compute Cloud instances, you must explicitly allow Amazon EC2 actions in the permissions policy, such as those in the **AmazonEC2FullAccess** managed policy. 

For more information about the SAML keys that you can check in a policy, see [Available keys for SAML-based AWS STS federation](reference_policies_iam-condition-keys.md#condition-keys-saml).

## Uniquely identifying users in SAML-based federation


When you create access policies in IAM, it's often useful to be able to specify permissions based on the identity of users. For example, for users who have been federated using SAML, an application might want to keep information in Amazon S3 using a structure like this: 

```
amzn-s3-demo-bucket/app1/user1
amzn-s3-demo-bucket/app1/user2
amzn-s3-demo-bucket/app1/user3
```

You can create the bucket (`amzn-s3-demo-bucket`) and folder (`app1`) through the Amazon S3 console or the AWS CLI, since those are static values. However, the user-specific folders (*user1*, *user2*, *user3*, etc.) have to be created at run time using code, since the value that identifies the user isn't known until the first time the user signs in through the federation process. 

To write policies that reference user-specific details as part of a resource name, the user identity has to be available in SAML keys that can be used in policy conditions. The following keys are available for SAML 2.0–based federation for use in IAM policies. You can use the values returned by the following keys to create unique user identifiers for resources like Amazon S3 folders. 
+ `saml:namequalifier`. A hash value based on the concatenation of the `Issuer` response value (`saml:iss`) and a string with the `AWS` account ID and the friendly name (the last part of the ARN) of the SAML provider in IAM. The concatenation of the account ID and friendly name of the SAML provider is available to IAM policies as the key `saml:doc`. The account ID and provider name must be separated by a '/' as in "123456789012/provider\$1name". For more information, see the `saml:doc` key at [Available keys for SAML-based AWS STS federation](reference_policies_iam-condition-keys.md#condition-keys-saml).

  The combination of `NameQualifier` and `Subject` can be used to uniquely identify a SAML federated principal. The following pseudocode shows how this value is calculated. In this pseudocode `+` indicates concatenation, `SHA1` represents a function that produces a message digest using SHA-1, and `Base64` represents a function that produces Base-64 encoded version of the hash output.

   `Base64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" ) )` 

   For more information about the policy keys that are available for SAML-based federation, see [Available keys for SAML-based AWS STS federation](reference_policies_iam-condition-keys.md#condition-keys-saml).
+ `saml:sub` (string). This is the subject of the claim, which includes a value that uniquely identifies an individual user within an organization (for example, `_cbb88bf52c2510eabe00c1642d4643f41430fe25e3`). 
+ `saml:sub_type` (string). This key can be `persistent`, `transient`, or the full `Format` URI from the `Subject` and `NameID` elements used in your SAML assertion. A value of `persistent` indicates that the value in `saml:sub` is the same for a user across all sessions. If the value is `transient`, the user has a different `saml:sub` value for each session. For information about the `NameID` element's `Format` attribute, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md). 

The following example shows a permission policy that uses the preceding keys to grant permissions to a user-specific folder in Amazon S3. The policy assumes that the Amazon S3 objects are identified using a prefix that includes both `saml:namequalifier` and `saml:sub`. Notice that the `Condition` element includes a test to be sure that `saml:sub_type` is set to `persistent`. If it is set to `transient`, the `saml:sub` value for the user can be different for each session, and the combination of values should not be used to identify user-specific folders. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": [
      "s3:GetObject",
      "s3:PutObject",
      "s3:DeleteObject"
    ],
    "Resource": [
      "arn:aws:s3:::amzn-s3-demo-bucket-org-data/backup/${saml:namequalifier}/${saml:sub}",
      "arn:aws:s3:::amzn-s3-demo-bucket-org-data/backup/${saml:namequalifier}/${saml:sub}/*"
    ],
    "Condition": {"StringEquals": {"saml:sub_type": "persistent"}}
  }
}
```

------

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": [
      "s3:GetObject",
      "s3:PutObject",
      "s3:DeleteObject"
    ],
    "Resource": [
      "arn:aws-cn:s3:::amzn-s3-demo-bucket-org-data/backup/${saml:namequalifier}/${saml:sub}",
      "arn:aws-cn:s3:::amzn-s3-demo-bucket-org-data/backup/${saml:namequalifier}/${saml:sub}/*"
    ],
    "Condition": {"StringEquals": {"saml:sub_type": "persistent"}}
  }
}
```

------

For more information about mapping assertions from the IdP to policy keys, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md). 

# Create a SAML identity provider in IAM
Create SAML identity provider

An IAM SAML 2.0 identity provider is an entity in IAM that describes an external identity provider (IdP) service that supports the [SAML 2.0 (Security Assertion Markup Language 2.0)](https://wiki.oasis-open.org/security) standard. You use an IAM identity provider when you want to establish trust between a SAML-compatible IdP such as Shibboleth or Active Directory Federation Services and AWS, so that your users can access AWS resources. IAM SAML identity providers are used as principals in an IAM trust policy. 

For more information about this scenario, see [SAML 2.0 federation](id_roles_providers_saml.md).

You can create and manage an IAM identity provider in the AWS Management Console or with AWS CLI, Tools for Windows PowerShell, or AWS API calls. 

After you create a SAML provider, you must create one or more IAM roles. A role is an identity in AWS that doesn't have its own credentials (as a user does). But in this context, a role is dynamically assigned to a SAML federated principal that is authenticated by your IdP. The role permits your IdP to request temporary security credentials for access to AWS. The policies assigned to the role determine what users are allowed to do in AWS. To create a role for SAML federation, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md). 

Finally, after you create the role, you complete the SAML trust by configuring your IdP with information about AWS and the roles that you want your SAML federated principals to use. This is referred to as configuring relying party trust between your IdP and AWS. To configure relying party trust, see [Configure your SAML 2.0 IdP with relying party trust and adding claims](id_roles_providers_create_saml_relying-party.md). 

**Topics**
+ [

## Prerequisites
](#idp-manage-identityprovider-prerequisites)
+ [

## Create and manage an IAM SAML identity provider (console)
](#idp-manage-identityprovider-console)
+ [

## Manage SAML encryption keys
](#id_federation_manage-saml-encryption)
+ [

## Create and manage an IAM SAML Identity Provider (AWS CLI)
](#idp-create-identityprovider-CLI)
+ [

## Create and manage an IAM SAML identity provider (AWS API)
](#idp-create-identityprovider-API)
+ [

## Next steps
](#id_roles_create-for-saml-next-steps)

## Prerequisites


Before you can create a SAML identity provider, you must have the following information from your IdP.
+ Get the SAML metadata document from your IdP. This document includes the issuer's name, expiration information, and keys that can be used to validate the SAML authentication response (assertions) that are received from the IdP. To generate the metadata document, use the identity management software provided by your external IdP.
**Important**  
This metadata file includes the issuer name, expiration information, and keys that can be used to validate the SAML authentication response (assertions) received from the IdP. The metadata file must be encoded in UTF-8 format without a byte order mark (BOM). To remove the BOM, you can encode the file as UTF-8 using a text editing tool, such as Notepad\$1\$1.  
The X.509 certificate included as part of the SAML metadata document must use a key size of at least 1024 bits. Also, the X.509 certificate must also be free of any repeated extensions. You can use extensions, but the extensions can only appear once in the certificate. If the X.509 certificate does not meet either condition, IdP creation fails and returns an "Unable to parse metadata" error.  
As defined by the [SAML V2.0 Metadata Interoperability Profile Version 1.0](https://docs.oasis-open.org/security/saml/Post2.0/sstc-metadata-iop-os.html), IAM does not evaluate or take action on the expiration of X.509 certificates in SAML metadata documents. If you are concerned about expired X.509 certificates, we recommend monitoring certificate expiration dates and rotating certificates according to your organization’s governance and security policies.
+ When you choose to enable SAML encryption, you must generate a private key file using your IdP, and upload this file to your IAM SAML configuration in .pem file format. AWS STS needs this private key to decrypt SAML responses that correspond to the public key uploaded to your IdP. The following algorithms are supported:
  + Encryption algorithms
    + AES-128
    + AES-256
    + RSA-OAEP
  + Key transport algorithms
    + AES-CBC
    + AES-GCM

  See your identity provider's documentation for steps to generate a private key.
**Note**  
IAM Identity Center and Amazon Cognito do not support encrypted SAML assertions from IAM SAML identity providers. You can indirectly add support for encrypted SAML assertions to Amazon Cognito identity pool federation with Amazon Cognito user pools. User pools have SAML federation that's independent of IAM SAML federation and supports [SAML signing and encryption](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-SAML-signing-encryption.html). Although this feature doesn't extend directly to identity pools, user pools can be IdPs to identity pools. To use SAML encryption with identity pools, add a SAML provider with encryption to a user pool that is an IdP to an identity pool.  
Your SAML provider must be able to encrypt SAML assertions with a key that your user pool provides. User pools won't accept assertions encrypted with a certificate that IAM has provided.

For instructions on how to configure many of the available IdPs to work with AWS, including how to generate the required SAML metadata document, see [Integrate third-party SAML solution providers with AWS](id_roles_providers_saml_3rd-party.md).

For help with SAML federation, see [Troubleshooting SAML federation](troubleshoot_saml.md).

## Create and manage an IAM SAML identity provider (console)


You can use the AWS Management Console to create, update, and delete IAM SAML identity providers. For help with SAML federation, see [Troubleshooting SAML federation](troubleshoot_saml.md).

**To create an IAM SAML identity provider (console)**

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, choose **Identity providers** and then choose **Add provider**. 

1. For **Configure provider**, choose **SAML**. 

1. Type a name for the identity provider.

1. For **Metadata document**, choose **Choose file**, specify the SAML metadata document that you downloaded in [Prerequisites](#idp-manage-identityprovider-prerequisites).
**Note**  
The `validUntil` or `cacheDuration` attribute in your SAML metadata document defines the **Valid until** date for the identity provider. If your SAML metadata document does not include a validity period attribute, the **Valid until** date will not match your X.509 certificate expiration date.  
IAM does not evaluate or take action on the expiration of X.509 certificates in SAML metadata documents. If you are concerned about expired X.509 certificates, we recommend monitoring certificate expiration dates and rotating certificates according to your organization’s governance and security policies.

1. (Optional) For **SAML encryption**, choose **Choose file** and select the private key file that you created in [Prerequisites](#idp-manage-identityprovider-prerequisites). Choose **Require encryption** to accept only encrypted requests from your IdP.

1. (Optional) For **Add tags**, you can add key–value pairs to help you identify and organize your IdPs. You can also use tags to control access to AWS resources. To learn more about tagging SAML identity providers, see [Tag IAM SAML identity providers](id_tags_saml.md).

   Choose **Add tag**. Enter values for each tag key-value pair. 

1. Verify the information that you have provided. When you are done, choose **Add provider**. 

1. Assign an IAM role to your identity provider. This role gives external user identities managed by your identity provider permissions to access AWS resources in your account. To learn more about creating roles for identity federation, see [Create a role for a third-party identity provider](id_roles_create_for-idp.md).
**Note**  
SAML IDPs used in a role trust policy must be in the same account that the role is in.

**To delete a SAML provider (console)**

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, choose **Identity providers**.

1. Select the radio button next to the identity provider that you want to delete.

1. Choose **Delete**. A new window opens.

1. Confirm that you want to delete the provider by typing the word `delete` in the field. Then, choose **Delete**.

## Manage SAML encryption keys


You can configure IAM SAML providers to receive encrypted assertions in the SAML response from your external IdP. Users can assume a role in AWS with encrypted SAML assertions by calling `[sts:AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html)`.

SAML encryption ensures that assertions are secure when passed through intermediaries or third parties. In addition, this feature helps you meet FedRAMP or any internal compliance policy requirements that mandate SAML assertions to be encrypted.

To configure an IAM SAML identity provider, see [Create a SAML identity provider in IAM](#id_roles_providers_create_saml). For help with SAML federation, see [Troubleshooting SAML federation](troubleshoot_saml.md).

### Rotate SAML encryption key


IAM uses the private key you uploaded to the IAM SAML provider to decrypt encrypted SAML assertions from your IdP. You can save up to two private key files for each identity provider, allowing you to rotate private keys as necessary. When two files are saved, each request will first attempt to decrypt with the newest **Added on** date, then IAM attempts to decrypt the request with the oldest **Added on** date.

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, choose **Identity providers** and then select your provider from the list. 

1. Choose the **SAML encryption** tab and choose **Add new key**.

1. Select **Choose file** and upload the private key you downloaded from your IdP as a .pem file.Then, choose **Add key**.

1. In the **Private keys for SAML decryption** section, select the expired private key file and choose **Remove**. We recommend you remove the expired private key after adding a new private key to ensure the first attempt to decrypt your assertion is successful.

## Create and manage an IAM SAML Identity Provider (AWS CLI)


You can use the AWS CLI to create, update, and delete SAML providers. For help with SAML federation, see [Troubleshooting SAML federation](troubleshoot_saml.md).

**To create an IAM identity provider and upload a metadata document (AWS CLI)**
+ Run this command: [https://docs.aws.amazon.com/cli/latest/reference/iam/create-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-saml-provider.html) 

**To update an IAM SAML identity provider (AWS CLI)**

You can update the metadata file, SAML encryption settings, and rotate private key decryption files for your IAM SAML provider. To rotate private keys, add your new private key and then remove the old key in a separate request. For more information about rotating private keys, see [Manage SAML encryption keys](#id_federation_manage-saml-encryption).
+ Run this command:[https://docs.aws.amazon.com/cli/latest/reference/iam/update-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/update-saml-provider.html) 

**To tag an existing IAM identity provider (AWS CLI)**
+ Run this command:[https://docs.aws.amazon.com/cli/latest/reference/iam/tag-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-saml-provider.html) 

**To list tags for existing IAM identity provider (AWS CLI)**
+ Run this command:[https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-provider-tags.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-provider-tags.html) 

**To remove tags on an existing IAM identity provider (AWS CLI)**
+ Run this command:[https://docs.aws.amazon.com/cli/latest/reference/iam/untag-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-saml-provider.html) 

**To delete an IAM SAML identity provider (AWS CLI)**

1. (Optional) To list information for all providers, such as the ARN, creation date, and expiration, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-providers.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-providers.html)

1. (Optional) To get information about a specific provider, such as the ARN, creation date, expiration date, encryption settings, and private key information, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/get-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-saml-provider.html)

1. To delete an IAM identity provider, run the following command:
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-saml-provider.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-saml-provider.html)

## Create and manage an IAM SAML identity provider (AWS API)


You can use the AWS API to create, update, and delete SAML providers. For help with SAML federation, see [Troubleshooting SAML federation](troubleshoot_saml.md).

**To create an IAM identity provider and upload a metadata document (AWS API)**
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateSAMLProvider.html)

**To update an IAM SAML identity provider (AWS API)**

You can update the metadata file, SAML encryption settings, and rotate private key decryption files for your IAM SAML provider. To rotate private keys, add your new private key and then remove the old key in a separate request. For more information about rotating private keys, see [Manage SAML encryption keys](#id_federation_manage-saml-encryption).
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSAMLProvider.html)

**To tag an existing IAM identity provider (AWS API)**
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagSAMLProvider.html)

**To list tags for an existing IAM identity provider (AWS API)**
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviderTags.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviderTags.html)

**To remove tags on an existing IAM identity provider (AWS API)**
+ Call this operation: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagSAMLProvider.html)

**To delete an IAM identity provider (AWS API)**

1. (Optional) To list information for all IdPs, such as the ARN, creation date, and expiration, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviders.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviders.html)

1. (Optional) To get information about a specific provider, such as the ARN, creation date, expiration date, encryption settings, and private key information, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetSAMLProvider.html)

1. To delete an IdP, call the following operation:
   + [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSAMLProvider.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSAMLProvider.html)

## Next steps


After you create a SAML identity provider, set up the relying party trust with your IdP. You can also use claims from your IdP's authentication response in policies to control access to a role.
+ You must tell the IdP about AWS as a service provider. This is called adding relying party trust between your IdP and AWS. The exact process for adding relying party trust depends on what IdP you're using. For details, see [Configure your SAML 2.0 IdP with relying party trust and adding claims](id_roles_providers_create_saml_relying-party.md).
+ When the IdP sends the response containing the claims to AWS, many of the incoming claims map to AWS context keys. You can use these context keys in IAM policies using the Condition element to control access to a role. For details, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md)

# Configure your SAML 2.0 IdP with relying party trust and adding claims
Configure relying party trust and claims

When you create an IAM identity provider and role for SAML access, you are telling AWS about the external identity provider (IdP) and what its users are allowed to do. Your next step is to then tell the IdP about AWS as a service provider. This is called adding *relying party trust* between your IdP and AWS. The exact process for adding relying party trust depends on what IdP you're using. For details, see the documentation for your identity management software. 

Many IdPs allow you to specify a URL from which the IdP can read an XML document that contains relying party information and certificates. For AWS, use the sign-in endpoint URL. The following example shows the URL format with the optional `region-code`.

`https://region-code.signin.aws.amazon.com/static/saml-metadata.xml`

If SAML encryption is required, the URL must include the unique identifier AWS assigns to your SAML provider, which you can find on the Identity provider detail page. The following example shows a regional sign-in URL that includes a unique identifier.

`https://region-code.signin.aws.amazon.com/static/saml/IdP-ID/saml-metadata.xml`

For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html). For the AWS value, you can also use the non-Regional endpoint `https://signin.aws.amazon.com/saml`.

If you can't specify a URL directly, then download the XML document from the preceding URL and import it into your IdP software. 

You also need to create appropriate claim rules in your IdP that specify AWS as a relying party. When the IdP sends a SAML response to the AWS endpoint, it includes a SAML *assertion* that contains one or more *claims*. A claim is information about the user and its groups. A claim rule maps that information into SAML attributes. This lets you make sure that SAML authentication responses from your IdP contain the necessary attributes that AWS uses in IAM policies to check permissions for SAML federated principals. For more information, see the following topics:
+  [Overview of the role to allow SAML-federated access to your AWS resources](id_roles_providers_saml.md#CreatingSAML-configuring-role). This topic discusses using SAML-specific keys in IAM policies and how to use them to restrict permissions for SAML federated principals.
+ [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md). This topic discusses how to configure SAML claims that include information about the user. The claims are bundled into a SAML assertion and included in the SAML response that is sent to AWS. You must ensure that the information needed by AWS policies is included in the SAML assertion in a form that AWS can recognize and use.
+  [Integrate third-party SAML solution providers with AWS](id_roles_providers_saml_3rd-party.md). This topic provides links to documentation provided by third-party organizations about how to integrate identity solutions with AWS. 

**Note**  
To improve federation resiliency, we recommend that you configure your IdP and AWS federation to support multiple SAML sign-in endpoints. For details, see the AWS Security Blog article [How to use regional SAML endpoints for failover](https://aws.amazon.com/blogs//security/how-to-use-regional-saml-endpoints-for-failover).

# Integrate third-party SAML solution providers with AWS


**Note**  
We recommend that you require your human users to use temporary credentials when accessing AWS. Have you considered using AWS IAM Identity Center? You can use IAM Identity Center to centrally manage access to multiple AWS accounts and provide users with MFA-protected, single sign-on access to all their assigned accounts from one place. With IAM Identity Center, you can create and manage user identities in IAM Identity Center or easily connect to your existing SAML 2.0 compatible identity provider. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the *AWS IAM Identity Center User Guide*.

The following links help you configure third-party SAML 2.0 identity provider (IdP) solutions to work with AWS federation. Check with your identity provider to determine whether they support SAML token encryption. For SAML encryption requirements, see [Manage SAML encryption keys](id_roles_providers_create_saml.md#id_federation_manage-saml-encryption).

**Tip**  
AWS Support engineers can assist customers who have business and enterprise support plans with some integration tasks that involve third-party software. For a current list of supported platforms and applications, see [What third-party software is supported?](https://aws.amazon.com/premiumsupport/faqs/#what3rdParty) in the *AWS Support FAQs*.


****  

| Solution | More information | 
| --- | --- | 
| Auth0 |  [Integrate with Amazon Web Services](https://auth0.com/docs/integrations/aws) – This page on the Auth0 documentation website has links to resources that describe how to set up single sign-on (SSO) with the AWS Management Console and includes a JavaScript example. You can configure Auth0 to pass [session tags](id_session-tags.md). For more information, see [Auth0 Announces Partnership with AWS for IAM Session Tags](https://auth0.com/blog/auth0-partners-with-aws-for-iam-session-tags/). | 
| Microsoft Entra |  [Tutorial: Microsoft Entra SSO integration with AWS Single-Account Access](https://learn.microsoft.com/en-us/azure/active-directory/saas-apps/amazon-web-service-tutorial) – This tutorial on the Microsoft website describes how to set up Microsoft Entra (formerly known as Azure AD) as an identity provider (IdP) using SAML federation. | 
| Centrify | [Configure Centrify and Use SAML for SSO to AWS](https://docs.centrify.com/Content/Applications/AppsWeb/AmazonSAML.htm) – This page on the Centrify website explains how to configure Centrify to use SAML for SSO to AWS. | 
| CyberArk | Configure [CyberArk](https://docs.cyberark.com/Product-Doc/OnlineHelp/Idaptive/Latest/en/Content/Applications/AppsWeb/AmazonSAML.htm) to provide Amazon Web Services (AWS) access to users logging in through SAML single sign-on (SSO) from the CyberArk User Portal. | 
| ForgeRock | The [ForgeRock Identity Platform](https://backstage.forgerock.com/docs/am/6.5/saml2-guide/#saml2-create-hosted-idp) integrates with AWS. You can configure ForgeRock to pass [session tags](id_session-tags.md). For more information, see [Attribute Based Access Control for Amazon Web Services](https://www.forgerock.com/blog/attribute-based-access-control-amazon-web-services). | 
| Google Workspace | [Amazon Web Services cloud application](https://support.google.com/a/answer/6194963) – This article on the Google Workspace Admin Help site describes how to configure Google Workspace as a SAML 2.0 IdP with AWS as the service provider. | 
| IBM | You can configure IBM to pass [session tags](id_session-tags.md). For more information, see [IBM Cloud Identity IDaaS one of first to support AWS session tags](https://community.ibm.com/community/user/security/blogs/adam-case/2019/11/25/ibm-cloud-identity-idaas-one-of-first-to-support-aws-session-tags). | 
| JumpCloud |  [Granting Access via IAM Roles for Single Sign On (SSO) with Amazon AWS](https://support.jumpcloud.com/support/s/article/Granting-Access-via-IAM-Roles-for-Single-Sign-On-SSO-with-Amazon-AWS) – This article on the JumpCloud website describes how to set up and enable SSO based on IAM roles for AWS. | 
| Matrix42 | [MyWorkspace Getting Started Guide](https://myworkspace.matrix42.com/documents/MyWorkspace-Getting-Started-with-AWS.pdf) – This guide describes how to integrate AWS identity services with Matrix42 MyWorkspace. | 
| Microsoft Active Directory Federation Services (AD FS) |  [Field Notes: Integrating Active Directory Federation Service with AWS IAM Identity Center](https://aws.amazon.com/blogs/architecture/field-notes-integrating-active-directory-federation-service-with-aws-single-sign-on/) – This post on the AWS Architecture Blog explains the authentication flow between AD FS and AWS IAM Identity Center (IAM Identity Center). IAM Identity Center supports identity federation with SAML 2.0, allowing integration with AD FS solutions. Users can sign in to the IAM Identity Center portal with their corporate credentials reducing the admin overhead of maintaining separate credentials on IAM Identity Center. You can also configure AD FS to pass [session tags](id_session-tags.md). For more information, see [Use attribute-based access control with AD FS to simplify IAM permissions management](https://aws.amazon.com/blogs/security/attribute-based-access-control-ad-fs-simplify-iam-permissions-management/).  | 
| miniOrange | [SSO for AWS](http://miniorange.com/amazon-web-services-%28aws%29-single-sign-on-%28sso%29) – This page on the miniOrange website describes how to establish secure access to AWS for enterprises and full control over access of AWS applications.  | 
| Okta |  [ Integrating the Amazon Web Services Command Line Interface Using Okta](https://support.okta.com/help/Documentation/Knowledge_Article/Integrating-the-Amazon-Web-Services-Command-Line-Interface-Using-Okta) – From this page on the Okta support site you can learn how to configure Okta for use with AWS. You can configure Okta to pass [session tags](id_session-tags.md). For more information, see [Okta and AWS Partner to Simplify Access Via Session Tags](https://www.okta.com/blog/2019/11/okta-and-aws-partner-to-simplify-access-via-session-tags/). | 
| Okta | [AWS Account Federation](https://help.okta.com/oie/en-us/Content/Topics/DeploymentGuides/AWS/aws-deployment.htm) – This section on the Okta website describes how to set up and enable IAM Identity Center for AWS. | 
| OneLogin | From the [OneLogin Knowledgebase](https://onelogin.service-now.com/support), search for SAML AWS for a list of articles that explain how to set up IAM Identity Center functionality between OneLogin and AWS for a single-role and multi-role scenarios. You can configure OneLogin to pass [session tags](id_session-tags.md). For more information, see [OneLogin and Session Tags: Attribute-Based Access Control for AWS Resources](https://www.onelogin.com/blog/aws-session-tags-integration). | 
| Ping Identity |  [PingFederate AWS Connector](https://support.pingidentity.com/s/marketplace-integration-details?recordId=a7i1W0000004HBwQAM) – View details about the PingFederate AWS Connector, a quick connection template to easily set up a single sign-on (SSO) and provisioning connection. Read documentation and download the latest PingFederate AWS Connector for integrations with AWS. You can configure Ping Identity to pass [session tags](id_session-tags.md). For more information, see [Announcing Ping Identity Support for Attribute-Based Access Control in AWS](https://support.pingidentity.com/s/document-item?bundleId=integrations&topicId=pon1571779451105.html).  | 
| RadiantLogic | [Radiant Logic Technology Partners](http://www.radiantlogic.com/about/partners/technology-partners/) – Radiant Logic's RadiantOne Federated Identity Service integrates with AWS to provide an identity hub for SAML-based SSO.  | 
| RSA | [Amazon Web Services - RSA Ready Implementation Guide](https://community.rsa.com/s/article/Amazon-Web-Services-RSA-Ready-Implementation-Guide) provides guidance for integrating AWS and RSA. For more information on SAML configuration, see [Amazon Web Services - SAML My Page SSO Configuration - RSA Ready Implementation Guide](https://community.rsa.com/s/article/Amazon-Web-Services-SAML-My-Page-SSO-Configuration-RSA-Ready-Implementation-Guide). | 
| Salesforce.com |  [How to configure SSO from Salesforce to AWS](https://developer.salesforce.com/page/Configuring-SAML-SSO-to-AWS) – This how-to article on the Salesforce.com developer site describes how to set up an identity provider (IdP) in Salesforce and configure AWS as a service provider.  | 
| SecureAuth |  [AWS - SecureAuth SAML SSO](https://docs.secureauth.com/2104/en/amazon-web-services--aws---idp-initiated--integration-guide.html) – This article on the SecureAuth website describes how to set up SAML integration with AWS for a SecureAuth appliance.  | 
| Shibboleth |  [How to Use Shibboleth for SSO to the AWS Management Console](https://aws.amazon.com/blogs/security/how-to-use-shibboleth-for-single-sign-on-to-the-aws-management-console) – This entry on the AWS Security Blog provides a step-by-step tutorial on how to set up Shibboleth and configure it as an identity provider for AWS. You can configure Shibboleth to pass [session tags](id_session-tags.md). | 

For more details, see the [IAM Partners](https://aws.amazon.com/iam/partners/) page on the AWS website. 

# Configure SAML assertions for the authentication response


After you have verified a user's identity in your organization, the external identity provider (IdP) sends an authentication response to the AWS sign-in endpoint URL. This response is a POST request that includes a SAML token that adheres to the [HTTP POST Binding for SAML 2.0](http://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf) standard and that contains the following elements, or *claims*. You configure these claims in your SAML-compatible IdP. Refer to the documentation for your IdP for instructions on how to enter these claims.

When the IdP sends the response containing the claims to AWS, many of the incoming claims map to AWS context keys. These context keys can be checked in IAM policies using the `Condition` element. A listing of the available mappings follows in the section [Mapping SAML attributes to AWS trust policy context keys](#saml-attribute-mapping).

## `Subject` and `NameID`


The response must include exactly one `SubjectConfirmation` element with a `SubjectConfirmationData` element that includes both the `NotOnOrAfter` attribute and a `Recipient` attribute. The Recipient attribute must include a value that matches the AWS sign-in endpoint URL. Your IdP may use the the term `ACS`, `Recipient`, or `Target` to refer to this attribute.

If SAML encryption is required, the sign-in URL must include the unique identifier AWS assigns to your SAML provider, which you can find on the Identity provider detail page. The following example shows the sign-in URL format with the optional `region-code`.

`https://region-code.signin.aws.amazon.com/saml`

In the following example, the sign-in URL includes a unique identifier, which requires /acs/ be appended to the sign-in path.

`https://region-code.signin.aws.amazon.com/saml/acs/IdP-ID`

For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html). For the AWS value, you can also use the global sign-in endpoint `https://signin.aws.amazon.com/saml`.

`NameID` elements can have the value persistent, transient, or consist of the full Format URI as provided by the IdP solution. A value of persistent indicates that the value in `NameID` is the same for a user between sessions. If the value is transient, the user has a different `NameID` value for each session. Single sign-on interactions support the following types of identifiers:
+ `urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`
+ `urn:oasis:names:tc:SAML:2.0:nameid-format:transient`
+ `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`
+ `urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified`
+ `urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName`
+ `urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName`
+ `urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos`
+ `urn:oasis:names:tc:SAML:2.0:nameid-format:entity`

The following excerpt shows an example. Substitute your own values for the marked ones.

```
<Subject>
  <NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">_cbb88bf52c2510eabe00c1642d4643f41430fe25e3</NameID>
  <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
    <SubjectConfirmationData NotOnOrAfter="2013-11-05T02:06:42.876Z" Recipient="https://region-code.signin.aws.amazon.com/saml/SAMLSP4SHN3UIS2D558H46"/>
  </SubjectConfirmation>
</Subject>
```

**Important**  
The `saml:aud` context key comes from the SAML *recipient* attribute because it is the SAML equivalent to the OIDC audience field, for example, `accounts.google.com:aud`.

## `PrincipalTag` SAML attribute


(Optional) You can use an `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}`. This element allows you to pass attributes as session tags in the SAML assertion. For more information about session tags, see [Pass session tags in AWS STS](id_session-tags.md).

To pass attributes as session tags, include the `AttributeValue` element that specifies the value of the tag. For example, to pass the tag key-value pairs `Project` = `Marketing` and `CostCenter` = `12345`, use the following attribute. Include a separate `Attribute` element for each tag.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/PrincipalTag:Project">
  <AttributeValue>Marketing</AttributeValue>
</Attribute>
<Attribute Name="https://aws.amazon.com/SAML/Attributes/PrincipalTag:CostCenter">
  <AttributeValue>12345</AttributeValue>
</Attribute>
```

To set the tags above as transitive, include another `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys`. This is an optional multivalued attribute that sets your session tags as transitive. Transitive tags persist when you use the SAML session to assume another role in AWS. This is known as [role chaining](id_roles.md#iam-term-role-chaining). For example, to set both the `Principal` and `CostCenter` tags as transitive, use the following attribute to specify the keys.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys">
  <AttributeValue>Project</AttributeValue>
  <AttributeValue>CostCenter</AttributeValue>
</Attribute>
```

## `Role` SAML attribute


You can use an `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/Role`. This element contains one or more `AttributeValue` elements that list the IAM identity provider and role to which the user is mapped by your IdP. The IAM role and IAM identity provider are specified as a comma-delimited pair of ARNs in the same format as the `RoleArn` and `PrincipalArn` parameters that are passed to [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html). This element must contain at least one role-provider pair (`AttributeValue` element), and can contain multiple pairs. If the element contains multiple pairs, then the user is asked to choose which role to assume when they use WebSSO to sign in to the AWS Management Console.

**Important**  
The value of the `Name` attribute in the `Attribute` tag is case-sensitive. It must be set to `https://aws.amazon.com/SAML/Attributes/Role` exactly.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/Role">
  <AttributeValue>arn:aws:iam::account-number:role/role-name1,arn:aws:iam::account-number:saml-provider/provider-name</AttributeValue>
  <AttributeValue>arn:aws:iam::account-number:role/role-name2,arn:aws:iam::account-number:saml-provider/provider-name</AttributeValue>
  <AttributeValue>arn:aws:iam::account-number:role/role-name3,arn:aws:iam::account-number:saml-provider/provider-name</AttributeValue>
</Attribute>
```

## `RoleSessionName` SAML attribute


You can use an `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/RoleSessionName`. This element contains one `AttributeValue` element that provides an identifier for the temporary credentials that are issued when the role is assumed. You can use this to associate the temporary credentials with the user who is using your application. This element is used to display user information in the AWS Management Console. The value in the `AttributeValue` element must be between 2 and 64 characters long, can contain only alphanumeric characters, underscores, and the following characters: **. , \$1 = @ -** (hyphen). It cannot contain spaces. The value is typically a user ID (`john`) or an email address (`johndoe@example.com`). It should not be a value that includes a space, like a user's display name (`John Doe`).

**Important**  
The value of the `Name` attribute in the `Attribute` tag is case-sensitive. It must be set to `https://aws.amazon.com/SAML/Attributes/RoleSessionName` exactly.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/RoleSessionName">
  <AttributeValue>user-id-name</AttributeValue>
</Attribute>
```

## `SessionDuration` SAML attribute


(Optional) You can use an `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/SessionDuration"`. This element contains one `AttributeValue` element that specifies how long the user can access the AWS Management Console before having to request new temporary credentials. The value is an integer representing the number of seconds for the session. The value can range from 900 seconds (15 minutes) to 43200 seconds (12 hours). If this attribute is not present, then the credential last for one hour (the default value of the `DurationSeconds` parameter of the `AssumeRoleWithSAML` API).

To use this attribute, you must configure the SAML provider to provide single sign-on access to the AWS Management Console through the console sign-in web endpoint at `https://region-code.signin.aws.amazon.com/saml`. For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html). You can optionally use the following URL: `https://signin.aws.amazon.com/static/saml`. Note that this attribute extends sessions only to the AWS Management Console. It cannot extend the lifetime of other credentials. However, if it is present in an `AssumeRoleWithSAML` API call, it can be used to *shorten* the duration of the session. The default lifetime of the credentials returned by the call is 60 minutes. 

Note, too, that if a `SessionNotOnOrAfter` attribute is also defined, then the ***lesser*** value of the two attributes, `SessionDuration` or `SessionNotOnOrAfter`, establishes the maximum duration of the console session.

When you enable console sessions with an extended duration the risk of compromise of the credentials rises. To help you mitigate this risk, you can immediately disable the active console sessions for any role by choosing **Revoke Sessions** on the **Role Summary** page in the IAM console. For more information, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md). 

**Important**  
The value of the `Name` attribute in the `Attribute` tag is case-sensitive. It must be set to `https://aws.amazon.com/SAML/Attributes/SessionDuration` exactly.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/SessionDuration">
  <AttributeValue>1800</AttributeValue>
</Attribute>
```

## `SourceIdentity` SAML attribute


(Optional) You can use an `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/SourceIdentity`. This element contains one `AttributeValue` element that provides an identifier for the person or application that is using an IAM role. The value for source identity persists when you use the SAML session to assume another role in AWS known as [role chaining](id_roles.md#iam-term-role-chaining). The value for source identity is present in the request for every action taken during the role session. The value that is set cannot be changed during the role session. Administrators can then use AWS CloudTrail logs to monitor and audit the source identity information to determine who performed actions with shared roles.

The value in the `AttributeValue` element must be between 2 and 64 characters long, can contain only alphanumeric characters, underscores, and the following characters: **. , \$1 = @ -** (hyphen). It cannot contain spaces. The value is typically an attribute that is associated with the user such as a user id (`john`) or an email address (`johndoe@example.com`). It should not be a value that includes a space, like a user's display name (`John Doe`). For more information about using source identity, see [Monitor and control actions taken with assumed roles](id_credentials_temp_control-access_monitor.md).

**Important**  
If your SAML assertion is configured to use the [`SourceIdentity`](#saml_sourceidentity) attribute, then your role trust policy must also include the `sts:SetSourceIdentity` action, otherwise the assume role operation will fail. For more information about using source identity, see [Monitor and control actions taken with assumed roles](id_credentials_temp_control-access_monitor.md).

To pass a source identity attribute, include the `AttributeValue` element that specifies the value of the source identity. For example, to pass the source identity `Diego` use the following attribute.

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/SourceIdentity">
  <AttributeValue>Diego</AttributeValue>
```

## Mapping SAML attributes to AWS trust policy context keys


The tables in this section list commonly used SAML attributes and how they map to trust policy condition context keys in AWS. You can use these keys to control access to a role. To do that, compare the keys to the values that are included in the assertions that accompany a SAML access request.

**Important**  
These keys are available only in IAM trust policies (policies that determine who can assume a role) and are not applicable to permissions policies.

In the eduPerson and eduOrg attributes table, values are typed either as strings or as lists of strings. For string values, you can test these values in IAM trust policies using `StringEquals` or `StringLike` conditions. For values that contain a list of strings, you can use the `ForAnyValue` and `ForAllValues` [policy set operators](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys) to test the values in trust policies.

**Note**  
You should include only one claim per AWS context key. If you include more than one, only one claim will be mapped. 

The following table shows eduPerson and eduOrg attributes.


| eduPerson or eduOrg attribute (`Name` key) | Maps to this AWS context key (`FriendlyName` key) | Type | 
| --- | --- | --- | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.1`   |   `eduPersonAffiliation`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.2`   |   `eduPersonNickname`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.3`   |   `eduPersonOrgDN`   |  String  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.4`   |   `eduPersonOrgUnitDN`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.5`   |   `eduPersonPrimaryAffiliation`   |  String  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.6`   |   `eduPersonPrincipalName`   |  String  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.7`   |   `eduPersonEntitlement`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.8`   |   `eduPersonPrimaryOrgUnitDN`   |  String  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.9`   |   `eduPersonScopedAffiliation`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.10`   |   `eduPersonTargetedID`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.1.1.11`   |   `eduPersonAssurance`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.2.1.2`   |   `eduOrgHomePageURI`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.2.1.3`   |   `eduOrgIdentityAuthNPolicyURI`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.2.1.4`   |   `eduOrgLegalName`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.2.1.5`   |   `eduOrgSuperiorURI`   |  List of strings  | 
|   `urn:oid:1.3.6.1.4.1.5923.1.2.1.6`   |   `eduOrgWhitePagesURI`   |  List of strings  | 
|   `urn:oid:2.5.4.3`   |   `cn`   |  List of strings  | 

The following table shows Active Directory attributes.


| AD attribute | Maps to this AWS context key | Type | 
| --- | --- | --- | 
|  `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name`  |  `name`  |  String  | 
|  `http://schemas.xmlsoap.org/claims/CommonName`  |  `commonName`  |  String  | 
|  `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname`  |  `givenName`  |  String  | 
|  `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname`  |  `surname`  |  String  | 
|  `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`  |  `mail`  |  String  | 
|  `http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid`  |  `uid`  |  String  | 

The following table shows X.500 attributes.


| X.500 attribute | Maps to this AWS context key | Type | 
| --- | --- | --- | 
|  `2.5.4.3`  |  `commonName`  |  String  | 
|  `2.5.4.4`  |  `surname`  |  String  | 
|  `2.4.5.42`  |  `givenName`  |  String  | 
|  `2.5.4.45`  |  `x500UniqueIdentifier`  |  String  | 
|  `0.9.2342.19200300100.1.1`  |  `uid`  |  String  | 
|  `0.9.2342.19200300100.1.3`  |  `mail`  |  String  | 
|  `0.9.2342.19200300.100.1.45`  |  `organizationStatus`  |  String  | 

# Enabling SAML 2.0 federated principals to access the AWS Management Console
Enable SAML federated principals access to AWS console

You can use a role to configure your SAML 2.0-compliant identity provider (IdP) and AWS to permit SAML federated principals to access the AWS Management Console. The role grants the user permissions to carry out tasks in the console. If you want to give SAML federated principals other ways to access AWS, see one of these topics:
+ AWS CLI: [Switch to an IAM role (AWS CLI)](id_roles_use_switch-role-cli.md)
+ Tools for Windows PowerShell: [Switch to an IAM role (Tools for Windows PowerShell)](id_roles_use_switch-role-twp.md)
+ AWS API: [Switch to an IAM role (AWS API)](id_roles_use_switch-role-api.md)

## Overview


The following diagram illustrates the flow for SAML-enabled single sign-on. 

**Note**  
This specific use of SAML differs from the more general one illustrated at [SAML 2.0 federation](id_roles_providers_saml.md) because this workflow opens the AWS Management Console on behalf of the user. This requires the use of the AWS sign-in endpoint instead of directly calling the `AssumeRoleWithSAML` API. The endpoint calls the API for the user and returns a URL that automatically redirects the user's browser to the AWS Management Console.

![\[Single sign-on (SSO) to the AWS Management Console using SAML\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/saml-based-sso-to-console.diagram.png)


The diagram illustrates the following steps:

1. The user browses to your organization's portal and selects the option to go to the AWS Management Console. In your organization, the portal is typically a function of your IdP that handles the exchange of trust between your organization and AWS. For example, in Active Directory Federation Services, the portal URL is: `https://ADFSServiceName/adfs/ls/IdpInitiatedSignOn.aspx` 

1. The portal verifies the user's identity in your organization.

1. The portal generates a SAML authentication response that includes assertions that identify the user and include attributes about the user. You can also configure your IdP to include a SAML assertion attribute called `SessionDuration` that specifies how long the console session is valid. You can also configure the IdP to pass attributes as [session tags](id_session-tags.md). The portal sends this response to the client browser.

1. The client browser is redirected to the AWS single sign-on endpoint and posts the SAML assertion. 

1. The endpoint requests temporary security credentials on behalf of the user and creates a console sign-in URL that uses those credentials. 

1. AWS sends the sign-in URL back to the client as a redirect.

1. The client browser is redirected to the AWS Management Console. If the SAML authentication response includes attributes that map to multiple IAM roles, the user is first prompted to select the role for accessing the console. 

From the user's perspective, the process happens transparently: The user starts at your organization's internal portal and ends up at the AWS Management Console, without ever having to supply any AWS credentials.

Consult the following sections for an overview of how to configure this behavior along with links to detailed steps.

## Configure your network as a SAML provider for AWS


Inside your organization's network, you configure your identity store (such as Windows Active Directory) to work with a SAML-based IdP like Windows Active Directory Federation Services, Shibboleth, etc. Using your IdP, you generate a metadata document that describes your organization as an IdP and includes authentication keys. You also configure your organization's portal to route user requests for the AWS Management Console to the AWS SAML endpoint for authentication using SAML assertions. How you configure your IdP to produce the metadata.xml file depends on your IdP. Refer to your IdP's documentation for instructions, or see [Integrate third-party SAML solution providers with AWS](id_roles_providers_saml_3rd-party.md) for links to the web documentation for many of the SAML providers supported.

## Create a SAML provider in IAM


Next, you sign in to the AWS Management Console and go to the IAM console. There you create a new SAML provider, which is an entity in IAM that holds information about your organization's IdP. As part of this process, you upload the metadata document produced by the IdP software in your organization in the previous section. For details, see [Create a SAML identity provider in IAM](id_roles_providers_create_saml.md). 

## Configure permissions in AWS for SAML federated principals


The next step is to create an IAM role that establishes a trust relationship between IAM and your organization's IdP. This role must identify your IdP as a principal (trusted entity) for purposes of federation. The role also defines what users authenticated by your organization's IdP are allowed to do in AWS. You can use the IAM console to create this role. When you create the trust policy that indicates who can assume the role, you specify the SAML provider that you created earlier in IAM. You also specify one or more SAML attributes that a user must match to be allowed to assume the role. For example, you can specify that only users whose SAML `[eduPersonOrgDN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_edupersonorgdn)` value is `ExampleOrg` are allowed to sign in. The role wizard automatically adds a condition to test the `saml:aud` attribute to make sure that the role is assumed only for sign-in to the AWS Management Console.

If SAML encryption is required, the sign-in URL must include the unique identifier AWS assigns to your SAML provider, which you can find on the Identity provider detail page. The trust policy for the role might look like this:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::111122223333:saml-provider/ExampleOrgSSOProvider"
            },
            "Action": "sts:AssumeRoleWithSAML",
            "Condition": {
                "StringEquals": {
                    "saml:edupersonorgdn": "ExampleOrg",
                    "saml:aud": "https://region-code.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46"
                }
            }
        }
    ]
}
```

------

**Note**  
SAML IDPs used in a role trust policy must be in the same account that the role is in.

We recommend using regional endpoints for the `saml:aud` attribute at `https://region-code.signin.aws.amazon.com/static/saml-metadata.xml`. For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html).

For the [permission policy](access_policies.md) in the role, you specify permissions as you would for any role, user, or group. For example, if users from your organization are allowed to administer Amazon EC2 instances, you explicitly allow Amazon EC2 actions in the permission policy. You can do this by assigning a [managed policy](access_policies_manage-attach-detach.md), such as the **Amazon EC2 Full Access** managed policy. 

For details about creating a role for a SAML IdP, see [Create a role for SAML 2.0 federation (console)](id_roles_create_for-idp_saml.md). 

## Finish configuration and create SAML assertions


Notify your SAML IdP that AWS is your service provider by installing the `saml-metadata.xml` file found at `https://region-code.signin.aws.amazon.com/static/saml-metadata.xml` or `https://signin.aws.amazon.com/static/saml-metadata.xml`. If SAMl encryption is required, the file is found at `https://region-code.signin.aws.amazon.com/static/saml/SAMLSP4SHN3UIS2D558H46/saml-metadata.xml`.

For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html). 

How you install that file depends on your IdP. Some providers give you the option to type the URL, whereupon the IdP gets and installs the file for you. Others require you to download the file from the URL and then provide it as a local file. Refer to your IdP documentation for details, or see [Integrate third-party SAML solution providers with AWS](id_roles_providers_saml_3rd-party.md) for links to the web documentation for many of the supported SAML providers.

You also configure the information that you want the IdP to pass as SAML attributes to AWS as part of the authentication response. Most of this information appears in AWS as condition context keys that you can evaluate in your policies. These condition keys ensure that only authorized users in the right contexts are granted permissions to access your AWS resources. You can specify time windows that restrict when the console may be used. You can also specify the maximum time (up to 12 hours) that users can access the console before having to refresh their credentials. For details, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md).

# View a SAML response in your browser
View SAML response in browser

The following procedures describe how to view the SAML response from your service provider from in your browser when troubleshooting a SAML 2.0–related issue. 

For all browsers, go to the page where you can reproduce the issue. Then follow the steps for the appropriate browser:

**Topics**
+ [

## Google Chrome
](#chrome)
+ [

## Mozilla Firefox
](#firefox)
+ [

## Apple Safari
](#safari)
+ [

## What to do with the Base64-encoded SAML response
](#whatnext)

## Google Chrome


**To view a SAML response in Chrome**

These steps were tested using version 106.0.5249.103 (Official Build) (arm64) of Google Chrome. If you use another version, you might need to adapt the steps accordingly.

1. Press **F12** to start the **Developer Tools** console.

1. Select the **Network** tab, and then select **Preserve log** in the upper left of the **Developer Tools** window.

1. Reproduce the issue.

1. (Optional) If the **Method** column is not visible in the **Developer Tools** **Network** log pane, right-click on any column label and choose **Method** to add the column.

1. Look for a **SAML Post** in the **Developer Tools** **Network** log pane. Select that row, and then view the **Payload** tab at the top. Look for the **SAMLResponse** element that contains the encoded request. The associated value is the Base64-encoded response.

## Mozilla Firefox


**To view a SAML response in Firefox**

This procedure was tested on version 105.0.3 (64-bit) of Mozilla Firefox. If you use another version, you might need to adapt the steps accordingly.

1. Press **F12** to start the **Web Developer Tools** console.

1. Select the **Network** tab. 

1. In the upper right of the **Web Developer Tools **window, choose options (the small gear icon). Select **Persist logs**. 

1. Reproduce the issue.

1. (Optional) If the **Method** column is not visible in the **Web Developer Tools** **Network** log pane, right-click on any column label and choose **Method** to add the column.

1. Look for a **POST** **SAML** in the table. Select that row, and then view the **Request** tab and find the **SAMLResponse** element. The associated value is the Base64-encoded response.

## Apple Safari


**To view a SAML response in Safari**

These steps were tested using version 16.0 (17614.1.25.9.10, 17614) of Apple Safari. If you use another version, you might need to adapt the steps accordingly.

1. Enable Web Inspector in Safari. Open the **Preferences** window, select the **Advanced** tab, and then select **Show Develop menu in the menu bar**.

1. Now you can open Web Inspector. Choose **Develop** in the menu bar, then select **Show Web Inspector**.

1. Select the **Network** tab.

1. In the upper left of the **Web Inspector** window, choose options (the small circle icon containing three horizontal lines). Select **Preserve Log**.

1. (Optional) If the **Method** column is not visible in the **Web Inspector** **Network** log pane, right-click on any column label and choose **Method** to add the column.

1. Reproduce the issue.

1. Look for a **POST** **SAML** in the table. Select that row, and then view the Headers tab.

1. Look for the **SAMLResponse** element that contains the encoded request. Scroll down to find `Request Data` with the name `SAMLResponse`. The associated value is the Base64-encoded response.

## What to do with the Base64-encoded SAML response


Once you find the Base64-encoded SAML response element in your browser, copy it and use your favorite Base-64 decoding tool to extract the XML tagged response.

**Security tip**  
Because the SAML response data that you are viewing might contain sensitive security data, we recommend that you do not use an *online* base64 decoder. Instead use a tool installed on your local computer that does not send your SAML data over the network.

**Built-in option for Windows systems (PowerShell):**

```
PS C:\> [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("base64encodedtext"))
```

**Built-in option for MacOS and Linux systems:**

```
$ echo "base64encodedtext" | base64 --decode
```

**Review the values in the decoded file**  
Review the values in the decoded SAML response file. 
+ Verify that the value for the saml:NameID attribute matches the username for the authenticated user.
+ Review the value for https://aws.amazon.com/SAML/Attributes/Role. The ARN and SAML provider are case sensitive, and the [ARN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) must match the resource in your account.
+ Review the value for https://aws.amazon.com/SAML/Attributes/RoleSessionName. The value must match the value in the [claim rule](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html).
+ If you configure the attribute value for an email address or an account name, then make sure that the values are correct. The values must correspond to the email address or account name of the authenticated user.

**Check for errors and confirm the configuration**  
Check whether the values contain errors, and confirm that the following configurations are correct.
+ The claim rules meet the required elements and all ARNs are correct. For more information, see [Configure your SAML 2.0 IdP with relying party trust and adding claims](id_roles_providers_create_saml_relying-party.md).
+ You uploaded the latest metadata file from your IdP into AWS in your SAML provider. For more information, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md).
+ You correctly configured the IAM role's trust policy. For more information, see [Methods to assume a role](id_roles_manage-assume.md).

# Federating AWS Identities to external services


IAM outbound identity federation enables your AWS workloads to securely access external services without storing long-term credentials. Your AWS workloads can request short-lived JSON Web Tokens (JWTs) from AWS Security Token Service (AWS STS) by calling the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API. These tokens are cryptographically signed, publicly verifiable and contain a comprehensive set of claims that assert your AWS workload's identity to external services. You can use these tokens with a wide range of third-party cloud providers, SaaS platforms, and self-hosted applications. External services verify the token's authenticity using AWS's verification keys published at well-known endpoints and use the information in the tokens to make authentication and authorization decisions.

Outbound identity federation eliminates the need to store long-term credentials such as API keys or passwords in your application code or environment variables, improving your security posture. You can control access to token generation and enforce token properties such as signing algorithms, permitted audiences and duration using IAM policies. All token requests are logged in AWS , providing complete audit trails for security monitoring and compliance reporting. You can also customize tokens with tags that appear as custom claims, enabling external services to implement fine-grained, attribute-based access control.

## Common use cases


Using outbound identity federation, your AWS workloads can securely:
+ Access resources and services in external cloud providers. For example, a Lambda function processing data can write results to an external cloud provider's storage service or query their database.
+ Integrate with external software-as-a-service (SaaS) providers for analytics, data processing, monitoring etc. For example, your Lambda functions can send metrics to observability platforms.
+ Authenticate with your own applications hosted on AWS, external cloud providers or on-premises data centers, enabling secure hybrid and multi-cloud architectures. For example, your AWS workloads can interact with containerized applications running in your on-premises Kubernetes cluster.

## How It Works


![\[alt text not found\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/outbound-use-cases.png)


1. The Lambda function calls the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API to request a JSON Web Token (JWT) from AWS Security Token Service (AWS STS).

1. AWS STS validates the request and returns a signed JWT to the Lambda function.

1. The Lambda function sends the JWT to the external service.

1. The external service extracts the issuer URL from the token, verifies it matches a known trusted issuer, and fetches AWS's verification keys and metadata from the OIDC discovery endpoint.

1. The external service uses the verification keys to verify the token's signature and validates claims such as expiration time, subject and audience.

1. After successful validation, the external service grants access to the Lambda function.

# Getting started with outbound identity federation


This guide shows you how to enable outbound identity federation for your AWS account and obtain your first JSON Web Token (JWT) (using the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API). You will enable the feature, establish a trust relationship with an external service, configure IAM permissions, and request a token using either AWS CLI or AWS SDK for Python (Boto3).

## Prerequisites


Before you begin, ensure you have:
+ Latest version of the AWS CLI or Python 3.8 (or later) and Boto3 installed (for AWS SDK examples)
+ An external service account where you can configure trust relationships (such as an external cloud provider, SaaS provider, or a test application)

**Note**  
The `GetWebIdentityToken` API is not available on the STS Global endpoint.
The JSON Web Tokens (JWTs) generated by the `GetWebIdentityToken` API cannot be used for OpenID Connect (OIDC) federation into AWS (via the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API).

## Enable outbound identity federation for your account


You must enable outbound identity federation before you can request tokens. You can enable the feature using the AWS Management Console or programmatically using the [EnableOutboundWebIdentityFederation](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableOutboundWebIdentityFederation.html) API.

### Using the AWS CLI


```
aws iam enable-outbound-web-identity-federation
```

### Using AWS SDK for Python


```
import boto3

# Create IAM client
iam_client = boto3.client('iam')

# Enable outbound identity federation
response = iam_client.enable_outbound_web_identity_federation()
print(f"Feature enabled. Issuer URL: {response['IssuerUrl']}")
print(f"Status: {response['Status']}")
```

### Using the AWS Console


Navigate to IAM and select **Account Settings** under the **Access Management** section of the left-hand navigation menu

![\[alt text not found\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/outbound-screen-1.png)


Once you enable the feature, make note of your account-specific issuer URL. You will use this URL when configuring trust relationships in external services. You can also retrieve this issuer URL as needed using the [GetOutboundWebIdentityFederationInfo](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOutboundWebIdentityFederationInfo.html) API.

![\[alt text not found\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/outbound-screen-2.png)


## Establish trust relationship in external service


Configure the external service to trust and accept tokens issued by your AWS account. The specific steps vary by service, but generally involve:
+ Registering your AWS account issuer URL as a trusted identity provider
+ Configuring which claims to validate (audience, subject patterns)
+ Mapping token claims to permissions in the external service

Refer to the external service documentation for detailed configuration instructions.

## Configure IAM permissions


Create an IAM policy that grants permission to call the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API and attach the policy to an IAM role that needs to generate tokens.

This example policy grants access to token generation with specific restrictions. It allows requesting tokens only for "https://api.example.com" as the audience and enforces a maximum token lifetime of 5 minutes (300 seconds). Refer to [IAM and AWS STS condition context keys](reference_policies_iam-condition-keys.md) for a list of condition keys you can use to enforce token properties.

### Example IAM policy


```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:GetWebIdentityToken",
            "Resource": "*",
            "Condition": {
                "ForAllValues:StringEquals": {
                    "sts:IdentityTokenAudience": "https://api.example.com"
                },
                "NumericLessThanEquals": {
                    "sts:DurationSeconds": 300
                }
            }
        }
    ]
}
```

## Request your first JSON Web Token (JWT)


You can request a JSON Web Token using the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API. You can specify the following parameters when calling the API:
+ **Audience (required):** The intended recipient of the token. This value populates the "aud" claim in the JWT. External services validate this claim to ensure the token was intended for them.
+ **SigningAlgorithm (required):** The cryptographic algorithm used to sign the token. Valid values are ES384 and RS256. Use ES384 for optimal security and performance, or RS256 for broader compatibility with systems that do not support ECDSA.
+ **DurationSeconds (optional):** The token lifetime in seconds. Valid values range from 60 to 3600. The default is 300 (5 minutes). We recommend shorter token lifetimes for increased security.
+ **Tags (optional):** A list of key-value pairs to include as custom claims in the token. External services can use these claims for fine-grained authorization.

The API returns the following fields:
+ **IdentityToken:** The signed JWT as a base64url-encoded string. Include this token in requests to external services.
+ **Expiration:** The UTC timestamp for when the token expires.

### Using the AWS CLI


```
aws sts get-web-identity-token \
    --audience "https://api.example.com" \
    --signing-algorithm ES384 \
    --duration-seconds 300 \
    --tags Key=team,Value=data-engineering \
           Key=environment,Value=production \
           Key=cost-center,Value=analytics
```

### Using AWS SDK for Python


```
import boto3

sts_client = boto3.client('sts')

response = sts_client.get_web_identity_token(
    Audience=['https://api.example.com'],
    DurationSeconds=300,
    SigningAlgorithm='RS256',
    Tags=[
        {'Key': 'team', 'Value': 'data-engineering'},
        {'Key': 'environment', 'Value': 'production'},
        {'Key': 'cost-center', 'Value': 'analytics'}
    ]
)

token = response['WebIdentityToken']
```

You can also decode the JWT to inspect its contents using standard JWT libraries like PyJWT, Python-jose for Python, Nimbus JOSE\$1JWT for Java or debuggers like jwt.io. Refer to [Understanding token claims](id_roles_providers_outbound_token_claims.md) for more information on claims included in the token.

## Use the token with an external service


After receiving the token, include it in requests to the external service. The method varies by service, but most services accept tokens in the Authorization header. The external service should implement token validation logic that fetches the JWKS keys from your issuer's well-known endpoint, verifies the token's signature, and validates essential claims before granting access to your AWS workloads.

## Fetch verification keys and metadata from the OpenID Connect (OIDC) endpoints


The unique issuer URL for your AWS account hosts the OpenID Connect (OIDC) discovery endpoints that contain verification keys and metadata necessary for token verification.

The OIDC discovery endpoint URL contains metadata some providers use to verify tokens. It is available at:

```
{issuer_url}/.well-known/openid-configuration
```

The JWKS (JSON Web Key Set) endpoint contains keys used to verify token signatures. It is available at:

```
{issuer_url}/.well-known/jwks.json
```

### Fetch JWKS using curl


```
curl https://{issuer_url}/.well-known/jwks.json
```

Response:

```
{
  "keys": [
    {
      "kty": "EC",
      "use": "sig",
      "kid": "key-id-1",
      "alg": "ES384",
      "crv": "P-384",
      "x": "base64-encoded-x-coordinate",
      "y": "base64-encoded-y-coordinate"
    },
    {
      "kty": "RSA",
      "use": "sig",
      "kid": "key-id-2",
      "n": "base64-encoded-modulus",
      "e": "AQAB"
    }
  ]
}
```

### Using AWS SDK for Python


```
import requests

# Fetch Openid Configuration
open_id_config_response = requests.get("https://{issuer_url}/.well-known/openid-configuration")
open_id_config = open_id_config_response.json()

# Fetch JWKS
jwks_response = requests.get("https://{issuer_url}/.well-known/jwks.json")
jwks = jwks_response.json()
```

We recommend caching these keys to avoid fetching them for every token verification.

### Essential claim validations

+ **Subject (sub):** Verify the subject claim contains the expected IAM principal ARN pattern.
+ **Expiration (exp):** Ensure the token has not expired. JWT libraries typically handle this automatically.
+ **Audience (aud):** Verify the audience matches your expected value. This prevents tokens intended for other services from being used with yours.
+ **Issuer (iss):** Verify the issuer matches the AWS account(s) you trust. Maintain a list of trusted issuer URLs.

Whenever possible, you should validate additional AWS-specific claims to implement fine-grained access control in your external service. For example, validate the org\$1id claim to restrict access to IAM principals in your AWS Organization, check principal\$1tags to enforce attribute-based access control (such as allowing only production environments or specific teams), or verify session context claims like lambda\$1source\$1function\$1arn or ec2\$1instance\$1source\$1vpc to restrict access based on the compute resource. Refer to [Understanding token claims](id_roles_providers_outbound_token_claims.md) for a full list of claims included in the token.

# Understanding token claims


When you call the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API, AWS Security Token Service returns a signed JSON Web Token (JWT) that contains a set of claims that represent the identity of the IAM principal. These tokens are compliant with [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519). Understanding the structure and contents of these tokens helps you implement secure authentication flows, configure appropriate claim validations in external services, and effectively use custom claims for fine-grained access control.

The JWT includes standard OpenID Connect (OIDC) claims such as subject ("sub"), audience ("aud"), issuer ("iss") to facilitate interoperability across different external services. AWS STS populates the token with AWS identity-specific claims (like the AWS Account ID and Principal tags) and session context claims (like EC2 instance ARNs) when applicable. You can also add custom claims to the token by passing them as request tags to the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API. The AWS identity-specific claims, and session context claims and custom claims are nested under the "https://sts.amazonaws.com/" namespace in the token.

Refer to the sample token below for a list of claims included in the token. Please note that all these claims may not be present in a token at the same time. 

```
{
  "iss": "https://abc123-def456-ghi789-jkl012.tokens.sts.global.api.aws",
  "aud": "https://api.example.com",
  "sub": "arn:aws:iam::123456789012:role/DataProcessingRole",
  "iat": 1700000000,
  "exp": 1700000900,
  "jti": "xyz123-def456-ghi789-jkl012",
  "https://sts.amazonaws.com/": {
    "aws_account": "123456789012",
    "source_region": "us-east-1",
    "org_id": "o-abc1234567",
    "ou_path": "o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/",
    "principal_tags": {
      "environment": "production",
      "team": "data-engineering",
      "cost-center": "engineering"
    },
    "lambda_source_function_arn": "arn:aws:lambda:us-east-1:123456789012:function:process-data",
    "request_tags": {
        "job-id": "job-2024-001",
        "priority": "high",
        "data-classification": "sensitive"
    }
  }
}
```

## Standard claims


The standard OIDC claims present in the tokens facilitate interoperability with a wide range of external services. These claims can be validated using most JWT libraries.


| Claim | Name | Description | Example Value | 
| --- | --- | --- | --- | 
| iss | Issuer | Your account-specific issuer URL. External services validate this claim to ensure it matches their trusted issuer. | https://abc123-def456-ghi789-jkl012.tokens.sts.global.api.aws | 
| aud | Audience | The intended recipient for the token specified in the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) request. | https://api.example.com | 
| sub | Subject | The ARN of the IAM principal that requested the token. | arn:aws:iam::123456789012:role/DataProcessingRole | 
| iat | Issued At | NumericDate value that identifies the time at which the JWT was issued. | 1700000000 | 
| exp | Expiration | NumericDate value that identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. | 1700000900 | 
| jti | JWT ID | Unique identifier for this token instance. | xyz123-def456-ghi789-jkl012 | 

## Custom claims


In addition to the standard OIDC claims, AWS STS adds claims about the identity and session context when applicable. You can also add your own claims to the token by passing them as request tags. Custom claims are nested under the https://sts.amazonaws.com/ namespace.

### AWS identity claims


These claims provide detailed information about your AWS account, organization structure, and IAM principal.


| Claim | Description | Maps to Condition Key | Example Value | 
| --- | --- | --- | --- | 
| aws\$1account | Your AWS account ID | [aws:PrincipalAccount](reference_policies_condition-keys.md#condition-keys-principalaccount) | 123456789012 | 
| source\$1region | The AWS region where the token was requested | [aws:RequestedRegion](reference_policies_condition-keys.md#condition-keys-requestedregion) | us-east-1 | 
| org\$1id | Your AWS Organizations ID (if your account is part of an organization) | [aws:PrincipalOrgID](reference_policies_condition-keys.md#condition-keys-principalorgid) | o-abc1234567 | 
| ou\$1path | Your organizational unit path (if applicable) | [aws:PrincipalOrgPaths](reference_policies_condition-keys.md#condition-keys-principalorgpaths) | o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/ | 
| principal\$1tags | Tags attached to the IAM principal or assumed role session. When a token is requested where the requesting IAM principal has both principal tags and session tags, the session tags will be present in the JWT. | [aws:PrincipalTag/<tag-key>](reference_policies_condition-keys.md#condition-keys-principaltag) | \$1"environment": "production", "team": "data-engineering", "cost-center":"engineering"\$1 | 

### Session context claims


These claims provide information about the compute environment and session where the token request originated. AWS AWS STS automatically includes these claims when applicable based on the requesting principal's session context.


| Claim | Description | Maps to Condition Key | Example Value | 
| --- | --- | --- | --- | 
| original\$1session\$1exp | When the original role session credentials will expire (for assumed roles) | N/A | 2024-01-15T10:00:00Z | 
| federated\$1provider | The identity provider name for federated sessions | [aws:FederatedProvider](reference_policies_condition-keys.md#condition-keys-federatedprovider) | arn:aws:iam::111122223333:oidc-provider/your\$1oidc\$1provider | 
| identity\$1store\$1user\$1id | IAM Identity Center user ID | [identitystore:UserId](reference_policies_condition-keys.md#condition-keys-identity-store-user-id) | user-abc123def456 | 
| identity\$1store\$1arn | ARN of the Identity Center identity store | [identitystore:IdentityStoreArn](https://docs.aws.amazon.com/singlesignon/latest/userguide/condition-context-keys-sts-idc.html#condition-keys-identity-store-arn) | arn:aws:identitystore::123456789012:identitystore/d-abc1234567 | 
| ec2\$1source\$1instance\$1arn | ARN of the requesting EC2 instance | [ec2:SourceInstanceArn](reference_policies_condition-keys.md#condition-keys-ec2-source-instance-arn) | arn:aws:ec2:us-east-1:123456789012:instance/i-abc123def456 | 
| ec2\$1instance\$1source\$1vpc | VPC ID where EC2 role credentials were delivered | [aws:Ec2InstanceSourceVpc](reference_policies_condition-keys.md#condition-keys-ec2instancesourcevpc) | vpc-abc123def456 | 
| ec2\$1instance\$1source\$1private\$1ipv4 | Private IPv4 address of the EC2 instance | [aws:Ec2InstanceSourcePrivateIPv4](reference_policies_condition-keys.md#condition-keys-ec2instancesourceprivateip4) | 10.0.1.25 | 
| ec2\$1role\$1delivery | Instance metadata service version | [ec2:RoleDelivery](reference_policies_condition-keys.md#condition-keys-ec2-role-delivery) | 2 | 
| source\$1identity | Source identity set by the principal | [aws:SourceIdentity](reference_policies_condition-keys.md#condition-keys-sourceidentity) | admin-user | 
| lambda\$1source\$1function\$1arn | ARN of the calling Lambda function | [lambda:SourceFunctionArn](reference_policies_condition-keys.md#condition-keys-lambda-source-function-arn) | arn:aws:lambda:us-east-1:123456789012:function:my-function | 
| glue\$1credential\$1issuing\$1service | AWS Glue service identifier for Glue jobs | [glue:CredentialIssuingService](reference_policies_condition-keys.md#condition-keys-glue-credential-issuing) | glue.amazonaws.com | 

### Request tags


You can add custom claims to tokens by specifying tags in the [GetWebIdentityToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API request. These claims appear under the request\$1tags field in the token and enable you to pass specific information that external services can use for fine-grained authorization decisions. You can specify up to 50 tags per request.

Example request:

```
response = sts_client.get_web_identity_token(
    Audience=['https://api.example.com'],
    SigningAlgorithm='ES384'
    Tags=[
        {'Key': 'team', 'Value': 'data-engineering'},
        {'Key': 'cost-center', 'Value': 'analytics'},
        {'Key': 'environment', 'Value': 'production'}
    ]
)
```

Resulting claims in token:

```
{
  "request_tags": {
    "team": "data-engineering",
    "cost-center": "analytics",
    "environment": "production"
  }
}
```

# Controlling access with IAM policies


IAM provides multiple policy types to control access to the outbound identity federation feature. You can use [identity-based policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) to control which IAM principals can request tokens and enforce specific token properties such as audience, lifetimes, and signing algorithms. [Service Control Policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) (SCPs) enable you to enforce organization-wide restrictions on token generation across all accounts in your AWS Organizations. [Resource Control Policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) (RCPs) control access at the resource level. You can also use [VPC endpoint policies](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-access.html) to restrict which principals can access the AWS STS `GetWebIdentityToken` API through your VPC endpoints, adding network-level controls to your security posture. This section explains how to implement fine-grained access controls using these policy types and condition keys.

To request identity tokens, an IAM principal must have the `sts:GetWebIdentityToken` permission. Grant this permission through identity policies attached to IAM users or roles. To allow Tags (key, value pairs) to be passed to the GetWebIdentityToken call, the IAM principal must have the `sts:TagGetWebIdentityToken` permission.
+ Use the [sts:IdentityTokenAudience](reference_policies_iam-condition-keys.md#ck_identitytokenaudience) condition key to limit which external services can receive tokens.
+ Use the [sts:DurationSeconds](reference_policies_iam-condition-keys.md#ck_durationseconds) condition key to enforce maximum token lifetimes.
+ Use the [sts:SigningAlgorithm](reference_policies_iam-condition-keys.md#ck_signingalgorithm) condition key to require specific cryptographic algorithms.
+ Use the [aws:RequestTag](reference_policies_condition-keys.md#condition-keys-requesttag) condition key compare the tag key-value pair that was passed in the request with the tag pair that you specify in the policy.
+ Use the [aws:TagKeys](reference_policies_condition-keys.md#condition-keys-tagkeys) condition key to compare the tag keys in a request with the keys that you specify in the policy.

Refer to [IAM and AWS STS](reference_policies_iam-condition-keys.md) condition keys to learn more about the condition keys available in IAM policies.

This sample identity policy combines multiple condition keys:

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowTokenGenerationWithRestrictions",
            "Effect": "Allow",
            "Action": "sts:GetWebIdentityToken",
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "sts:IdentityTokenAudience": [
                        "https://api1.example.com",
                        "https://api2.example.com"
                    ]
                },
                "NumericLessThanEquals": {
                    "sts:DurationSeconds": 300
                },
                "StringEquals": {
                    "sts:SigningAlgorithm": "ES384"
                }
            }
        }
    ]
}
```

## Best practices


Follow these recommendations to securely federate your AWS identities to external services.
+ **Use short token lifetimes:** Request tokens with the shortest lifetime that meets your operational needs.
+ **Implement least privilege access and restrict token properties with IAM policies:** Grant the `sts:GetWebIdentityToken` permission only to IAM principals that require it. Use condition keys to specify signing algorithms, permitted token audiences, and maximum token lifetimes as you require.
+ **Validate claims in external services:** For security, always validate relevant claims such as subject ("sub"), audience ("aud") etc. to ensure they match your expected values. Validate custom claims when possible to enable fine-grain authorization decisions in external services.

# Temporary security credentials in IAM
Temporary security credentials

You can use the AWS Security Token Service (AWS STS) to create and provide trusted users with temporary security credentials that can control access to your AWS resources. Temporary security credentials work almost identically to long-term access key credentials, with the following differences:
+ Temporary security credentials are *short-term*, as the name implies. They can be configured to last for anywhere from a few minutes to several hours. After the credentials expire, AWS no longer recognizes them or allows any kind of access from API requests made with them.
+ Temporary security credentials are not stored with the user but are generated dynamically and provided to the user when requested. When (or even before) the temporary security credentials expire, the user can request new credentials, as long as the user requesting them still has permissions to do so.

As a result, temporary credentials have the following advantages over long-term credentials:
+ You do not have to distribute or embed long-term AWS security credentials with an application.
+ You can provide access to your AWS resources to users without having to define an AWS identity for them. Temporary credentials are the basis for [roles](id_roles.md) and [identity federation](id_roles_providers.md).
+ The temporary security credentials have a limited lifetime, so you do not have to update them or explicitly revoke them when they're no longer needed. After temporary security credentials expire, they cannot be reused. You can specify how long the credentials are valid, up to a maximum limit. 

## AWS STS and AWS regions


Temporary security credentials are generated by AWS STS. By default, AWS STS is a global service with a single endpoint at `https://sts.amazonaws.com`. However, you can also choose to make AWS STS API calls to endpoints in any other supported Region. This can reduce latency (server lag) by sending the requests to servers in a Region that is geographically closer to you. No matter which Region your credentials come from, they work globally. For more information, see [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).

## Common scenarios for temporary credentials


Temporary credentials are useful in scenarios that involve identity federation, delegation, cross-account access, and IAM roles.

### Identity federation


You can manage your user identities in an external system outside of AWS and grant users who sign in from those systems access to perform AWS tasks and access your AWS resources. IAM supports two types of identity federation. In both cases, the identities are stored outside of AWS. The distinction is where the external system resides—in your data center or an external third party on the web. To compare features of temporary security credentials for identity federation, see [Compare AWS STS credentials](id_credentials_sts-comparison.md).

For more information about external identity providers, see [Identity providers and federation into AWS](id_roles_providers.md).
+ **OpenID Connect (OIDC) federation** – You can let users sign in using a well-known third-party identity provider such as Login with Amazon, Facebook, Google, or any OIDC 2.0 compatible provider for your mobile or web application, you don't need to create custom sign-in code or manage your own user identities. Using OIDC federation helps you keep your AWS account secure, because you don't have to distribute long-term security credentials, such as IAM user access keys, with your application. For more information, see [OIDC federation](id_roles_providers_oidc.md).

  AWS STS OIDC federation supports Login with Amazon, Facebook, Google, and any OpenID Connect (OIDC)-compatible identity provider.
**Note**  
For mobile applications, we recommend that you use Amazon Cognito. You can use this service with AWS SDKs for mobile development to create unique identities for users and authenticate them for secure access to your AWS resources. Amazon Cognito supports the same identity providers as AWS STS, and also supports unauthenticated (guest) access and lets you migrate user data when a user signs in. Amazon Cognito also provides API operations for synchronizing user data so that it is preserved as users move between devices. For more information, see [Authentication with Amplify](https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/#authentication-with-amplify) in the *Amplify Documentation*.
+ **SAML federation** – You can authenticate users in your organization's network, and then provide those users access to AWS without creating new AWS identities for them and requiring them to sign in with different sign-in credentials. This is known as the *single sign-on* approach to temporary access. AWS STS supports open standards like Security Assertion Markup Language (SAML) 2.0, with which you can use Microsoft AD FS to leverage your Microsoft Active Directory. You can also use SAML 2.0 to manage your own solution for federating user identities. For more information, see [SAML 2.0 federation](id_roles_providers_saml.md).
  + **Custom federation broker** – You can use your organization's authentication system to grant access to AWS resources. For an example scenario, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).
  + **Federation using SAML 2.0** – You can use your organization's authentication system and SAML to grant access to AWS resources. For more information and an example scenario, see [SAML 2.0 federation](id_roles_providers_saml.md).

### Roles for cross-account access


Many organizations maintain more than one AWS account. Using roles and cross-account access, you can define user identities in one account, and use those identities to access AWS resources in other accounts that belong to your organization. This is known as the *delegation* approach to temporary access. For more information about creating cross-account roles, see [Create a role to give permissions to an IAM user](id_roles_create_for-user.md). To learn whether principals in accounts outside of your zone of trust (trusted organization or account) have access to assume your roles, see [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html).

### Roles for Amazon EC2


If you run applications on Amazon EC2 instances and those applications need access to AWS resources, you can provide temporary security credentials to your instances when you launch them. These temporary security credentials are available to all applications that run on the instance, so you don't need to store any long-term credentials on the instance. For more information, see [Use an IAM role to grant permissions to applications running on Amazon EC2 instances](id_roles_use_switch-role-ec2.md).

To learn more about IAM Amazon EC2 role credentials, see [IAM roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) in the *Amazon Elastic Compute Cloud User Guide*.

### Other AWS services


You can use temporary security credentials to access most AWS services. For a list of the services that accept temporary security credentials, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md).

## Sample applications that use temporary credentials


You can use AWS Security Token Service (AWS STS) to create and provide trusted users with temporary security credentials that can control access to your AWS resources. For more information about AWS STS, see [Temporary security credentials in IAM](#id_credentials_temp). To see how you can use AWS STS to manage temporary security credentials, you can download the following sample applications that implement complete example scenarios:
+ [Enabling Federation to AWS Using Windows Active Directory, ADFS, and SAML 2.0](https://aws.amazon.com/blogs/security/enabling-federation-to-aws-using-windows-active-directory-adfs-and-saml-2-0/). Demonstrates how to delgate access using enterprise federation to AWS using Windows Active Directory (AD), Active Directory Federation Services (ADFS) 2.0, and SAML (Security Assertion Markup Language) 2.0.
+ [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md). Demonstrates how to create a custom federation proxy that enables single sign-on (SSO) so that existing Active Directory users can sign in to the AWS Management Console.
+ [How to Use Shibboleth for Single Sign-On to the AWS Management Console.](https://aws.amazon.com/blogs/security/how-to-use-shibboleth-for-single-sign-on-to-the-aws-management-console/). Shows how to use [Shibboleth](http://shibboleth.net/) and [SAML](id_roles_providers_saml.md) to provide users with single sign-on (SSO) access to the AWS Management Console.

### Samples for OIDC federation


The following sample applications illustrate how to use OIDCfederation with providers like Login with Amazon, Amazon Cognito, Facebook, or Google. You can trade authentication from these providers for temporary AWS security credentials to access AWS services.
+ [Amazon Cognito Tutorials](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorials.html) – We recommend that you use Amazon Cognito with the AWS SDKs for mobile development. Amazon Cognito is the simplest way to manage identity for mobile apps, and it provides additional features like synchronization and cross-device identity. For more information about Amazon Cognito, see [Authentication with Amplify](https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/#authentication-with-amplify) in the *Amplify Documentation*.

## Additional resources for temporary security credentials
Additional resources for temporary credentials

The following scenarios and applications can guide you in using temporary security credentials: 
+ [How to integrate AWS STS SourceIdentity with your identity provider](https://aws.amazon.com/blogs/security/how-to-integrate-aws-sts-sourceidentity-with-your-identity-provider/). This post shows you how to set up the AWS STS `SourceIdentity` attribute when using Okta, Ping, or OneLogin as your IdP.
+  [OIDC federation](id_roles_providers_oidc.md). This section discusses how to configure IAM roles when you use OIDC federation and the `AssumeRoleWithWebIdentity` API. 
+ [Secure API access with MFA](id_credentials_mfa_configure-api-require.md). This topic explains how to use roles to require multi-factor authentication (MFA) to protect sensitive API actions in your account.

For more information on policies and permissions in AWS see the following topics:
+ [Access management for AWS resources](access.md)
+ [Policy evaluation logic](reference_policies_evaluation-logic.md).
+ [Managing Access Permissions to Your Amazon S3 Resources](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-access-control.html) in *Amazon Simple Storage Service User Guide*.
+  To learn whether principals in accounts outside of your zone of trust (trusted organization or account) have access to assume your roles, see [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html).

# Compare AWS STS credentials


The following table compares features of the API operations in AWS STS that return temporary security credentials. To learn about the different methods you can use to request temporary security credentials by assuming a role, see [Methods to assume a role](id_roles_manage-assume.md). To learn about the different AWS STS API operations that allow you to pass session tags, see [Pass session tags in AWS STS](id_session-tags.md).

**Note**  
You can send AWS STS API calls either to a global endpoint or to one of the Regional endpoints. If you choose an endpoint closer to you, you can reduce latency and improve the performance of your API calls. You also can choose to direct your calls to an alternative Regional endpoint if you can no longer communicate with the original endpoint. If you are using one of the various AWS SDKs, then use that SDK method to specify a Region before you make the API call. If you manually construct HTTP API requests, then you must direct the request to the correct endpoint yourself. For more information, see the [AWS STS section of *Regions and Endpoints*](https://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) and [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).


|  **AWS STS API**  |  **Who can call**  |  **Credential lifetime (min \$1 max \$1 default)**  |  **MFA support**¹  |  **Session policy support**²  |  **Restrictions on resulting temporary credentials**  | 
| --- | --- | --- | --- | --- | --- | 
|  [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)  | IAM user or IAM role with existing temporary security credentials  | 15 m \$1 Maximum session duration setting³ \$1 1 hr  | Yes  | Yes |  Cannot call `GetFederationToken` or `GetSessionToken`.  | 
|  [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html)  | Any user; caller must pass a SAML authentication response that indicates authentication from a known identity provider | 15 m \$1 Maximum session duration setting³ \$1 1 hr  | No | Yes |  Cannot call `GetFederationToken` or `GetSessionToken`.  | 
|  [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html)  | Any user; caller must pass an OIDC compliant JWT token that indicates authentication from a known identity provider | 15 m \$1 Maximum session duration setting³ \$1 1 hr  | No | Yes |  Cannot call `GetFederationToken` or `GetSessionToken`.  | 
| [GetFederationToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) | IAM user or AWS account root user |  IAM user: 15 m \$1 36 hr \$1 12 hr Root user: 15 m \$1 1 hr \$1 1 hr  | No  | Yes  |  Cannot call IAM operations using the AWS CLI or AWS API. This limitation does not apply to console sessions. Cannot call AWS STS operations except `GetCallerIdentity`.⁴ SSO to console is allowed.⁵  | 
| [GetSessionToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) | IAM user or AWS account root user |  IAM user: 15 m \$1 36 hr \$1 12 hr Root user: 15 m \$1 1 hr \$1 1 hr  | Yes  | No  |  Cannot call IAM API operations unless MFA information is included with the request. Cannot call AWS STS API operations except `AssumeRole` or `GetCallerIdentity`. SSO to console is not allowed.⁶  | 

 ¹ **MFA support**. You can include information about a multi-factor authentication (MFA) device when you call the AssumeRole and GetSessionToken API operations. This ensures that the temporary security credentials that result from the API call can be used only by users who are authenticated with an MFA device. For more information, see [Secure API access with MFA](id_credentials_mfa_configure-api-require.md). 

 ² **Session policy support**. Session policies are policies that you pass as a parameter when you programmatically create a temporary session for a role or AWS STS federated user session. This policy limits the permissions from the role or user's identity-based policy that are assigned to the session. The resulting session's permissions are the intersection of the entity's identity-based policies and the session policies. Session policies cannot be used to grant more permissions than those allowed by the identity-based policy of the role that is being assumed. For more information about role session permissions, see [Session policies](access_policies.md#policies_session).

³ **Maximum session duration setting**. Use the `DurationSeconds` parameter to specify the duration of your role session from 900 seconds (15 minutes) up to the maximum session duration setting for the role. To learn how to view the maximum value for your role, see [Update the maximum session duration for a role](id_roles_update-role-settings.md#id_roles_update-session-duration).

⁴ **GetCallerIdentity**. No permissions are required to perform this operation. If an administrator adds a policy to your IAM user or role that explicitly denies access to the `sts:GetCallerIdentity` action, you can still perform this operation. Permissions are not required because the same information is returned when an IAM user or role is denied access. To view an example response, see [I am not authorized to perform: iam:DeleteVirtualMFADevice](troubleshoot.md#troubleshoot_general_access-denied-delete-mfa).

⁵ **Single sign-on (SSO) to the console**. To support SSO, AWS lets you call a federation endpoint (`https://signin.aws.amazon.com/federation`) and pass temporary security credentials. The endpoint returns a token that you can use to construct a URL that signs a user directly into the console without requiring a password. For more information, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md) and [ How to Enable Cross-Account Access to the AWS Management Console](https://aws.amazon.com/blogs/security/how-to-enable-cross-account-access-to-the-aws-management-console) in the AWS Security Blog. 

⁶ After you retrieve your temporary credentials, you can't access the AWS Management Console by passing the credentials to the federation single sign-on endpoint. For more information, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).

# Service bearer tokens


Some AWS services require that you have permission to get an AWS STS service bearer token before you can access their resources programmatically. These services support a protocol that requires you to use a bearer token instead of using a traditional [AWS Signature Version 4 for API requests](reference_sigv.md). When you perform AWS CLI or AWS API operations that require bearer tokens, the AWS service requests a bearer token on your behalf. The service provides you with the token, which you can then use to perform subsequent operations in that service. 

AWS STS service bearer tokens include information from your original principal authentication that might affect your permissions. This information can include principal tags, session tags, and session policies. The token's access key ID begins with the `ABIA` prefix. This helps you to identify operations that were performed using service bearer tokens in your CloudTrail logs.

**Important**  
The bearer token can be used only for calls to the service that generates it and in the Region where it was generated. You can't use the bearer token to perform operations in other services or Regions.

An example of a service that supports bearer tokens is AWS CodeArtifact. Before you can interact with AWS CodeArtifact using a package manager such as NPM, Maven, or PIP, you must call the `aws codeartifact get-authorization-token` operation. This operation returns a bearer token that you can use to perform AWS CodeArtifact operations. Alternatively, you can use the `aws codeartifact login` command that completes the same operation and then configures your client automatically. 

If you perform an action in an AWS service that generates a bearer token for you, you must have the following permissions in your IAM policy:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowServiceBearerToken",
            "Effect": "Allow",
            "Action": "sts:GetServiceBearerToken",
            "Resource": "*"
        }
    ]
}
```

------

For a service bearer token example, see [ Using identity-based policies for AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/auth-and-access-control-iam-identity-based-access-control.html) in the *AWS CodeArtifact* user guide.

# Request temporary security credentials


To request temporary security credentials, you can use AWS Security Token Service (AWS STS) operations in the AWS API. These include operations to create and provide trusted users with temporary security credentials that can control access to your AWS resources. For more information about AWS STS, see [Temporary security credentials in IAM](id_credentials_temp.md). To learn about the different methods that you can use to request temporary security credentials by assuming a role, see [Methods to assume a role](id_roles_manage-assume.md).

To call the API operations, you can use one of the [AWS SDKs](http://aws.amazon.com/tools/). The SDKs are available for a variety of programming languages and environments, including Java, .NET, Python, Ruby, Android, and iOS. The SDKs take care of tasks such as cryptographically signing your requests, retrying requests if necessary, and handling error responses. You can also use the AWS STS Query API, which is described in the [AWS Security Token Service API Reference](https://docs.aws.amazon.com/STS/latest/APIReference/). Finally, two command line tools support the AWS STS commands: the [AWS Command Line Interface](https://aws.amazon.com/documentation/cli), and the [AWS Tools for Windows PowerShell](https://aws.amazon.com/documentation/powershell). 

The AWS STS API operations create a new session with temporary security credentials that include an access key pair and a session token. The access key pair consists of an access key ID and a secret key. Users (or an application that the user runs) can use these credentials to access your resources. You can create a role session and pass session policies and session tags programmatically using AWS STS API operations. The resulting session permissions are the intersection of the role's identity-based policies and the session policies. For more information about session policies, see [Session policies](access_policies.md#policies_session). For more information about session tags, see [Pass session tags in AWS STS](id_session-tags.md).

**Note**  
The size of the session token that AWS STS API operations return is not fixed. We strongly recommend that you make no assumptions about the maximum size. The typical token size is less than 4096 bytes, but that can vary.

## Using AWS STS with AWS Regions


You can send AWS STS API calls either to a global endpoint or to one of the Regional endpoints. If you choose an endpoint closer to you, you can reduce latency and improve the performance of your API calls. You also can choose to direct your calls to an alternative Regional endpoint if you can no longer communicate with the original endpoint. If you are using one of the various AWS SDKs, then use that SDK method to specify a Region before you make the API call. If you manually construct HTTP API requests, then you must direct the request to the correct endpoint yourself. For more information, see the [AWS STS section of *Regions and Endpoints*](https://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) and [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).

The following are the API operations that you can use to acquire temporary credentials for use in your AWS environment and applications.

## Requesting credentials for cross-account delegation and federation through a custom identity broker
Requesting credentials with AssumeRole

The [https://docs.aws.amazon.com//STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com//STS/latest/APIReference/API_AssumeRole.html) API operation is useful for allowing existing IAM users to access AWS resources that they don't already have access to. For example, the user might need access to resources in another AWS account. It is also useful as a means to temporarily gain privileged access—for example, to provide multi-factor authentication (MFA). You must call this API using active credentials. To learn who can call this operation, see [Compare AWS STS credentials](id_credentials_sts-comparison.md). For more information, see [Create a role to give permissions to an IAM user](id_roles_create_for-user.md) and [Secure API access with MFA](id_credentials_mfa_configure-api-require.md).

**To request temporary security credentials for cross-account delegation and federation through a custom identity broker**

1. Authenticate with your AWS security credentials. This call must be made using valid AWS security credentials.

1. Call the operation [https://docs.aws.amazon.com//STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com//STS/latest/APIReference/API_AssumeRole.html).

The following example shows a sample request and response using `AssumeRole`. This example request assumes the `demo` role for the specified duration with the included [session policy](access_policies.md#policies_session), [session tags](id_session-tags.md), [external ID](id_roles_common-scenarios_third-party.md), and [source identity](id_credentials_temp_control-access_monitor.md). The resulting session is named `John-session`. 

**Example request**  

```
https://sts.amazonaws.com/
?Version=2011-06-15
&Action=AssumeRole
&RoleSessionName=John-session
&RoleArn=arn:aws::iam::123456789012:role/demo
&Policy=%7B%22Version%22%3A%222012-10-17		 	 	 %22%2C%22Statement%22%3A%5B%7B%22Sid%22%3A%20%22Stmt1%22%2C%22Effect%22%3A%20%22Allow%22%2C%22Action%22%3A%20%22s3%3A*%22%2C%22Resource%22%3A%20%22*%22%7D%5D%7D
&DurationSeconds=1800
&Tags.member.1.Key=Project
&Tags.member.1.Value=Pegasus
&Tags.member.2.Key=Cost-Center
&Tags.member.2.Value=12345
&ExternalId=123ABC
&SourceIdentity=DevUser123
&AUTHPARAMS
```

The policy value shown in the preceding example is the URL-encoded version of the following policy:

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

****  

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

------

The `AUTHPARAMS` parameter in the example is a placeholder for your *signature*. A signature is the authentication information that you must include with AWS HTTP API requests. We recommend using the [AWS SDKs](https://aws.amazon.com/tools/) to create API requests, and one benefit of doing so is that the SDKs handle request signing for you. If you must create and sign API requests manually, see [Signing AWS Requests By Using Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *Amazon Web Services General Reference* to learn how to sign a request.

In addition to the temporary security credentials, the response includes the Amazon Resource Name (ARN) for the federated user and the expiration time of the credentials.

**Example response**  

```
<AssumeRoleResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
<AssumeRoleResult>
<SourceIdentity>DevUser123</SourceIdentity>
<Credentials>
  <SessionToken>
   AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQW
   LWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGd
   QrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU
   9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz
   +scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==
  </SessionToken>
  <SecretAccessKey>
   wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY
  </SecretAccessKey>
  <Expiration>2019-07-15T23:28:33.359Z</Expiration>
  <AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>
</Credentials>
<AssumedRoleUser>
  <Arn>arn:aws:sts::123456789012:assumed-role/demo/John</Arn>
  <AssumedRoleId>ARO123EXAMPLE123:John</AssumedRoleId>
</AssumedRoleUser>
<PackedPolicySize>8</PackedPolicySize>
</AssumeRoleResult>
<ResponseMetadata>
<RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId>
</ResponseMetadata>
</AssumeRoleResponse>
```

**Note**  
An AWS conversion compresses the passed session policies and session tags into a packed binary format that has a separate limit. Your request can fail for this limit even if your plaintext meets the other requirements. The `PackedPolicySize` response element indicates by percentage how close the policies and tags for your request are to the upper size limit.

## Requesting credentials through an OIDC provider
Requesting credentials with AssumeRoleWithWebIdentity

The [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation returns a set of temporary AWS security credentials in exchange for a JSON Web Token (JWT). This includes public identity providers, such as Login with Amazon, Facebook, Google, and providers that issue JWTs that are compatible with OpenID Connect (OIDC) discovery, such as GitHub actions or Azure Devops. For more information, see [OIDC federation](id_roles_providers_oidc.md).

**Note**  
`AssumeRoleWithWebIdentity` requests are not signed with, and do not require AWS credentials.

**Requesting credentials through an OIDC provider**

1. Call the operation [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html).

   When you call `AssumeRoleWithWebIdentity`, AWS validates the token presented by verifying the digital signature using public keys made available through your IdP's JSON web keyset (JWKS). If the token is valid, and all conditions set forth in the IAM role trust policy are met, AWS returns the following information to you:
   + A set of temporary security credentials. These consist of an access key ID, a secret access key, and a session token.
   + The role ID and the ARN of the assumed role.
   + A `SubjectFromWebIdentityToken` value that contains the unique user ID.

1. Your application may then use the temporary security credentials that were returned in the response to make AWS API calls. This is the same process as making an AWS API call with long-term security credentials. The difference is that you must include the session token, which lets AWS verify that the temporary security credentials are valid.

Your application should cache the credentials returned by AWS STS and refresh them as needed. If your application is built using an AWS SDK, the SDK has credential providers that can handle calling `AssumeRoleWithWebIdentity` and refreshing AWS credentials before they expire. For more information, see [AWS SDKs and Tools standardized credential providers](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

## Requesting credentials through a SAML 2.0 identity provider
Requesting credentials with AssumeRoleWithSAML

The [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API operation returns a set of temporary security credentials for SAML federated principals who are authenticated by your organization's existing identity system. The users must also use [SAML](https://www.oasis-open.org/standards#samlv2.0) 2.0 (Security Assertion Markup Language) to pass authentication and authorization information to AWS. This API operation is useful in organizations that have integrated their identity systems (such as Windows Active Directory or OpenLDAP) with software that can produce SAML assertions. Such an integration provides information about user identity and permissions (such as Active Directory Federation Services or Shibboleth). For more information, see [SAML 2.0 federation](id_roles_providers_saml.md).

1. Call the operation [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html).

   This is an unsigned call, meaning you do not need to authenticate AWS security credentials prior to making the request.
**Note**  
A call to `AssumeRoleWithSAML` is not signed (encrypted). Therefore, you should only include optional session policies if the request is transmitted through a trusted intermediary. In this case, someone could alter the policy to remove the restrictions.

1. When you call `AssumeRoleWithSAML`, AWS verifies the authenticity of the SAML assertion. Assuming that the identity provider validates the assertion, AWS returns the following information to you:
   + A set of temporary security credentials. These consist of an access key ID, a secret access key, and a session token. 
   + The role ID and the ARN of the assumed role. 
   + An `Audience` value that contains the value of the `Recipient` attribute of the `SubjectConfirmationData` element of the SAML assertion.
   + An `Issuer` value that contains the value of the `Issuer` element of the SAML assertion.
   + A `NameQualifier` element that contains a hash value built from the `Issuer` value, the AWS account ID, and the friendly name of the SAML provider. When combined with the `Subject` element, they can uniquely identify the SAML federated principal.
   + A `Subject` element that contains the value of the `NameID` element in the `Subject` element of the SAML assertion.
   + A `SubjectType` element that indicates the format of the `Subject` element. The value can be `persistent`, `transient`, or the full `Format` URI from the `Subject` and `NameID` elements used in your SAML assertion. For information about the `NameID` element's `Format` attribute, see [Configure SAML assertions for the authentication response](id_roles_providers_create_saml_assertions.md). 

1. Use the temporary security credentials returned in the response to make AWS API calls. This is the same process as making an AWS API call with long-term security credentials. The difference is that you must include the session token, which lets AWS verify that the temporary security credentials are valid.

Your app should cache the credentials. By default the credentials expire after an hour. If you are not using the [AmazonSTSCredentialsProvider](https://aws.amazon.com/blogs/mobile/using-the-amazoncredentialsprovider-protocol-in-the-aws-sdk-for-ios) action in the AWS SDK, it's up to you and your app to call `AssumeRoleWithSAML` again. Call this operation to get a new set of temporary security credentials before the old ones expire.

## Requesting credentials through a custom identity broker
Requesting credentials with GetFederationToken

The [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API operation returns a set of temporary security credentials for AWS STS federated user principals. This API differs from `AssumeRole` in that the default expiration period is substantially longer (12 hours instead of one hour). Additionally, you can use the `DurationSeconds` parameter to specify a duration for the temporary security credentials to remain valid. The resulting credentials are valid for the specified duration, between 900 seconds (15 minutes) to 129,600 seconds (36 hours). The longer expiration period can help reduce the number of calls to AWS because you do not need to get new credentials as often.

1. Authenticate with the AWS security credentials of your specific IAM user. This call must be made using valid AWS security credentials.

1. Call the operation [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html).

The `GetFederationToken` call returns temporary security credentials that consist of the session token, access key, secret key, and expiration. You can use `GetFederationToken` if you want to manage permissions inside your organization (for example, using the proxy application to assign permissions).

The following example shows a sample request and response that uses `GetFederationToken`. This example request federates the calling user for the specified duration with the [session policy](access_policies.md#policies_session) ARN and [session tags](id_session-tags.md). The resulting session is named `Jane-session`.

**Example request**  

```
https://sts.amazonaws.com/
?Version=2011-06-15
&Action=GetFederationToken
&Name=Jane-session
&PolicyArns.member.1.arn==arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FRole1policy
&DurationSeconds=1800
&Tags.member.1.Key=Project
&Tags.member.1.Value=Pegasus
&Tags.member.2.Key=Cost-Center
&Tags.member.2.Value=12345
&AUTHPARAMS
```

The policy ARN shown in the preceding example includes the following URL-encoded ARN: 

`arn:aws:iam::123456789012:policy/Role1policy`

Also, note that the `&AUTHPARAMS` parameter in the example is meant as a placeholder for the authentication information. This is the *signature*, which you must include with AWS HTTP API requests. We recommend using the [AWS SDKs](https://aws.amazon.com/tools/) to create API requests, and one benefit of doing so is that the SDKs handle request signing for you. If you must create and sign API requests manually, go to [Signing AWS Requests By Using Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *Amazon Web Services General Reference* to learn how to sign a request.

In addition to the temporary security credentials, the response includes the Amazon Resource Name (ARN) for the federated user and the expiration time of the credentials.

**Example response**  

```
<GetFederationTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
<GetFederationTokenResult>
<Credentials>
  <SessionToken>
   AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQW
   LWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGd
   QrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU
   9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz
   +scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCEXAMPLE==
  </SessionToken>
  <SecretAccessKey>
  wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY
  </SecretAccessKey>
  <Expiration>2019-04-15T23:28:33.359Z</Expiration>
  <AccessKeyId>AKIAIOSFODNN7EXAMPLE;</AccessKeyId>
</Credentials>
<FederatedUser>
  <Arn>arn:aws:sts::123456789012:federated-user/Jean</Arn>
  <FederatedUserId>123456789012:Jean</FederatedUserId>
</FederatedUser>
<PackedPolicySize>4</PackedPolicySize>
</GetFederationTokenResult>
<ResponseMetadata>
<RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId>
</ResponseMetadata>
</GetFederationTokenResponse>
```

**Note**  
An AWS conversion compresses the passed session policies and session tags into a packed binary format that has a separate limit. Your request can fail for this limit even if your plaintext meets the other requirements. The `PackedPolicySize` response element indicates by percentage how close the policies and tags for your request are to the upper size limit.

AWS recommends that you grant permissions at the resource level (for example, you attach a resource-based policy to an Amazon S3 bucket), you can omit the `Policy` parameter. However, if you do not include a policy for the AWS STS federated user principal, the temporary security credentials will not grant any permissions. In this case, you *must* use resource policies to grant the federated user access to your AWS resources.

For example, assume your AWS account number is 111122223333, and you have an Amazon S3 bucket that you want to allow Susan to access. Susan's temporary security credentials don't include a policy for the bucket. In that case, you would need to ensure that the bucket has a policy with an ARN that matches Susan's ARN, such as `arn:aws:sts::111122223333:federated-user/Susan`. 

## Requesting credentials for users in untrusted environments
Requesting credentials with GetSessionToken

The [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) API operation returns a set of temporary security credentials to an existing IAM user. This is useful for providing enhanced security, such as allowing AWS requests only when MFA is enabled for the IAM user. Because the credentials are temporary, they provide enhanced security when you have an IAM user who accesses your resources through a less secure environment. Examples of less secure environments include a mobile device or web browser.

1. Authenticate with the AWS security credentials of your specific IAM user. This call must be made using valid AWS security credentials.

1. Call the operation [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html).

1. `GetSessionToken` returns temporary security credentials consisting of a session token, an access key ID, and a secret access key.

By default, temporary security credentials for an IAM user are valid for a maximum of 12 hours. But you can request a duration as short as 15 minutes or as long as 36 hours using the `DurationSeconds` parameter. For security reasons, a token for an AWS account root user is restricted to a duration of one hour.

The following example shows a sample request and response using `GetSessionToken`. The response also includes the expiration time of the temporary security credentials. 

**Example request**  

```
https://sts.amazonaws.com/
?Version=2011-06-15
&Action=GetSessionToken
&DurationSeconds=1800
&AUTHPARAMS
```

The `AUTHPARAMS` parameter in the example is a placeholder for your *signature*. A signature is the authentication information that you must include with AWS HTTP API requests. We recommend using the [AWS SDKs](https://aws.amazon.com/tools/) to create API requests, and one benefit of doing so is that the SDKs handle request signing for you. If you must create and sign API requests manually, go to [Signing AWS Requests By Using Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *Amazon Web Services General Reference* to learn how to sign a request.

**Example response**  

```
<GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
<GetSessionTokenResult>
<Credentials>
  <SessionToken>
   AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/L
   To6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3z
   rkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtp
   Z3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE
  </SessionToken>
  <SecretAccessKey>
  wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY
  </SecretAccessKey>
  <Expiration>2011-07-11T19:55:29.611Z</Expiration>
  <AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>
</Credentials>
</GetSessionTokenResult>
<ResponseMetadata>
<RequestId>58c5dbae-abef-11e0-8cfe-09039844ac7d</RequestId>
</ResponseMetadata>
</GetSessionTokenResponse>
```

Optionally, the `GetSessionToken` request can include `SerialNumber` and `TokenCode` values for AWS multi-factor authentication (MFA) verification. If the provided values are valid, AWS STS provides temporary security credentials that include the state of MFA authentication. The temporary security credentials can then be used to access the MFA-protected API operations or AWS websites for as long as the MFA authentication is valid. 

The following example shows a `GetSessionToken` request that includes an MFA verification code and device serial number. 

```
https://sts.amazonaws.com/
?Version=2011-06-15
&Action=GetSessionToken
&DurationSeconds=7200
&SerialNumber=YourMFADeviceSerialNumber
&TokenCode=123456
&AUTHPARAMS
```

**Note**  
The call to AWS STS can be to the global endpoint or to any of the Regional endpoints that you activate your AWS account. For more information, see the [AWS STS section of *Regions and Endpoints*](https://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region).  
The `AUTHPARAMS` parameter in the example is a placeholder for your *signature*. A signature is the authentication information that you must include with AWS HTTP API requests. We recommend using the [AWS SDKs](https://aws.amazon.com/tools/) to create API requests, and one benefit of doing so is that the SDKs handle request signing for you. If you must create and sign API requests manually, see [Signing AWS Requests By Using Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *Amazon Web Services General Reference* to learn how to sign a request.

# Use temporary credentials with AWS resources


You can use temporary security credentials to make programmatic requests for AWS resources using the AWS CLI or AWS API (using the [AWS SDKs](https://aws.amazon.com/tools/)). The temporary credentials provide the same permissions as long-term security credentials, such as IAM user credentials. However, there are a few differences:
+ When you make a call using temporary security credentials, the call must include a session token, which is returned along with those temporary credentials. AWS uses the session token to validate the temporary security credentials. 
+ Temporary credentials expire after a specified interval. After temporary credentials expire, any calls that you make with those credentials will fail, so you must generate a new set of temporary credentials. Temporary credentials cannot be extended or refreshed beyond the original specified interval.
+ When you use temporary credentials to make a request, your principal might include a set of tags. These tags come from session tags and tags that are attached to the role that you assume. For more information about session tags, see [Pass session tags in AWS STS](id_session-tags.md).

If you are using the [AWS SDKs](https://aws.amazon.com/tools), the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/) (AWS CLI), or the [Tools for Windows PowerShell](https://aws.amazon.com/powershell), the way to get and use temporary security credentials differs with the context. If you are running code, AWS CLI, or Tools for Windows PowerShell commands inside an EC2 instance, you can take advantage of roles for Amazon EC2. Otherwise, you can call an [AWS STS API](https://docs.aws.amazon.com/STS/latest/APIReference/) to get the temporary credentials, and then use them explicitly to make calls to AWS services.

**Note**  
You can use AWS Security Token Service (AWS STS) to create and provide trusted users with temporary security credentials that can control access to your AWS resources. For more information about AWS STS, see [Temporary security credentials in IAM](id_credentials_temp.md). AWS STS is a global service that has a default endpoint at `https://sts.amazonaws.com`. This endpoint is in the US East (N. Virginia) Region, although credentials that you get from this and other endpoints are valid globally. These credentials work with services and resources in any Region. You can also choose to make AWS STS API calls to endpoints in any of the supported Regions. This can reduce latency by making the requests from servers in a Region that is geographically closer to you. No matter which Region your credentials come from, they work globally. For more information, see [Manage AWS STS in an AWS Region](id_credentials_temp_enable-regions.md).

**Contents**
+ [

## Using temporary credentials in Amazon EC2 instances
](#using-temp-creds-sdk-ec2-instances)
+ [

## Using temporary security credentials with the AWS SDKs
](#using-temp-creds-sdk)
+ [

## Using temporary security credentials with the AWS CLI
](#using-temp-creds-sdk-cli)
+ [

## Using temporary security credentials with API operations
](#RequestWithSTS)
+ [

## More information
](#using-temp-creds-more-info)

## Using temporary credentials in Amazon EC2 instances


If you want to run AWS CLI commands or code inside an EC2 instance, the recommended way to get credentials is to use [roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html). You create an IAM role that specifies the permissions that you want to grant to applications that run on the EC2 instances. When you launch the instance, you associate the role with the instance.

Applications, AWS CLI, and Tools for Windows PowerShell commands that run on the instance can then get automatic temporary security credentials from the instance metadata. You do not have to explicitly get the temporary security credentials. The AWS SDKs, AWS CLI, and Tools for Windows PowerShell automatically get the credentials from the EC2 Instance Metadata Service (IMDS) and use them. The temporary credentials have the permissions that you define for the role that is associated with the instance.

For more information and for examples, see the following:
+  [Using IAM Roles to Grant Access to AWS Resources on Amazon Elastic Compute Cloud](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java-dg-roles.html) — AWS SDK for Java
+  [Granting Access Using an IAM Role](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html) — AWS SDK for .NET 
+  [Creating a Role](https://docs.aws.amazon.com/sdk-for-ruby/latest/developer-guide/iam-example-create-role.html) — AWS SDK for Ruby

## Using temporary security credentials with the AWS SDKs


To use temporary security credentials in code, you programmatically call an AWS STS API like `AssumeRole` and extract the resulting credentials and session token. You then use those values as credentials for subsequent calls to AWS. The following example shows pseudocode for how to use temporary security credentials if you're using an AWS SDK:

```
assumeRoleResult = AssumeRole(role-arn);
tempCredentials = new SessionAWSCredentials(
   assumeRoleResult.AccessKeyId, 
   assumeRoleResult.SecretAccessKey, 
   assumeRoleResult.SessionToken);
s3Request = CreateAmazonS3Client(tempCredentials);
```

For an example written in Python (using the [AWS SDK for Python (Boto)](https://aws.amazon.com/sdk-for-python/)), see [Switch to an IAM role (AWS API)](id_roles_use_switch-role-api.md). This example shows how to call `AssumeRole` to get temporary security credentials and then use those credentials to make a call to Amazon S3.

For details about how to call `AssumeRole`, `GetFederationToken`, and other API operations, see the [AWS Security Token Service API Reference](https://docs.aws.amazon.com/STS/latest/APIReference/). For information on getting the temporary security credentials and session token from the result, see the documentation for the SDK that you're working with. You can find the documentation for all the AWS SDKs on the main [AWS documentation page](http://aws.amazon.com/documentation), in the **SDKs and Toolkits** section.

You must make sure that you get a new set of credentials before the old ones expire. In some SDKs, you can use a provider that manages the process of refreshing credentials for you; check the documentation for the SDK you're using. 

## Using temporary security credentials with the AWS CLI


You can use temporary security credentials with the AWS CLI. This can be useful for testing policies. 

Using the [AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/), you can call an [AWS STS API](https://docs.aws.amazon.com/STS/latest/APIReference/) like `AssumeRole` or `GetFederationToken` and then capture the resulting output. The following example shows a call to `AssumeRole` that sends the output to a file. In the example, the `profile` parameter is assumed to be a profile in the AWS CLI configuration file. It is also assumed to reference credentials for an IAM user who has permissions to assume the role.

```
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/role-name --role-session-name "RoleSession1" --profile IAM-user-name > assume-role-output.txt
```

When the command is finished, you can extract the access key ID, secret access key, and session token from wherever you've routed it. You can do this either manually or by using a script. You can then assign these values to environment variables. 

When you run AWS CLI commands, the AWS CLI looks for credentials in a specific order—first in environment variables and then in the configuration file. Therefore, after you've put the temporary credentials into environment variables, the AWS CLI uses those credentials by default. (If you specify a `profile` parameter in the command, the AWS CLI skips the environment variables. Instead, the AWS CLI looks in the configuration file, which lets you override the credentials in the environment variables if you need to.) 

The following example shows how you might set the environment variables for temporary security credentials and then call an AWS CLI command. Because no `profile` parameter is included in the AWS CLI command, the AWS CLI looks for credentials first in environment variables and therefore uses the temporary credentials. 

**Linux**

```
$ export AWS_ACCESS_KEY_ID=ASIAIOSFODNN7EXAMPLE
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
$ export AWS_SESSION_TOKEN=AQoDYXdzEJr...<remainder of session token>
$ aws ec2 describe-instances --region us-west-1
```

**Windows**

```
C:\> SET AWS_ACCESS_KEY_ID=ASIAIOSFODNN7EXAMPLE
C:\> SET AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
C:\> SET AWS_SESSION_TOKEN=AQoDYXdzEJr...<remainder of token> 
C:\> aws ec2 describe-instances --region us-west-1
```

## Using temporary security credentials with API operations


If you're making direct HTTPS API requests to AWS, you can sign those requests with the temporary security credentials that you get from the AWS Security Token Service (AWS STS). To do this, you use the access key ID and secret access key that you receive from AWS STS. You use the access key ID and secret access key the same way you would use long-term credentials to sign a request. You also add to your API request the session token that you receive from AWS STS. You add the session token to an HTTP header or to a query string parameter named `X-Amz-Security-Token`. You add the session token to the HTTP header *or* the query string parameter, but not both. For more information about signing HTTPS API requests, see [Signing AWS API Requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) in the *AWS General Reference*.

## More information


For more information about using AWS STS with other AWS services, see the following links:
+ **Amazon S3**. See [Making requests using IAM user temporary credentials](https://docs.aws.amazon.com/AmazonS3/latest/userguide/AuthUsingTempSessionToken.html) or [Making requests using federated user temporary credentials](https://docs.aws.amazon.com/AmazonS3/latest/userguide/AuthUsingTempFederationToken.html) in the *Amazon Simple Storage Service User Guide*.
+ **Amazon SNS**. See [Using identity-based policies with Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/UsingIAMwithSNS.html#UsingTemporarySecurityCredentials_SNS) in the *Amazon Simple Notification Service Developer Guide*.
+ **Amazon SQS**. See [Identity and access management in Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/UsingIAM.html#UsingTemporarySecurityCredentials_SQS) in the *Amazon Simple Queue Service Developer Guide*.
+ **Amazon SimpleDB**. See [Using Temporary Security Credentials](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/index.html?UsingTemporarySecurityCredentials_SDB.html) in the *Amazon SimpleDB Developer Guide*.

# Permissions for temporary security credentials


You can use AWS Security Token Service (AWS STS) to create and provide trusted users with temporary security credentials that can control access to your AWS resources. For more information about AWS STS, see [Temporary security credentials in IAM](id_credentials_temp.md). After AWS STS issues temporary security credentials, they are valid through the expiration period and cannot be revoked. However, the permissions assigned to temporary security credentials are evaluated each time a request is made that uses the credentials, so you can achieve the effect of revoking the credentials by changing their access rights after they have been issued. 

The following topics assume you have a working knowledge of AWS permissions and policies. For more information on these topics, see [Access management for AWS resources](access.md). 

**Topics**
+ [

# Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity
](id_credentials_temp_control-access_assumerole.md)
+ [

# Monitor and control actions taken with assumed roles
](id_credentials_temp_control-access_monitor.md)
+ [

# Permissions for GetFederationToken
](id_credentials_temp_control-access_getfederationtoken.md)
+ [

# Permissions for GetSessionToken
](id_credentials_temp_control-access_getsessiontoken.md)
+ [

# Disabling permissions for temporary security credentials
](id_credentials_temp_control-access_disable-perms.md)
+ [

# Granting permissions to create temporary security credentials
](id_credentials_temp_control-access_enable-create.md)
+ [

# Granting permissions to use identity-enhanced console sessions
](id_credentials_temp_control-access_sts-setcontext.md)

# Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity
Permissions for AssumeRole API operations

The permissions policy of the role that is being assumed determines the permissions for the temporary security credentials that are returned by `AssumeRole`, `AssumeRoleWithSAML`, and `AssumeRoleWithWebIdentity`. You define these permissions when you create or update the role. 

Optionally, you can pass inline or managed [session policies](access_policies.md#policies_session) as parameters of the `AssumeRole`, `AssumeRoleWithSAML`, or `AssumeRoleWithWebIdentity` API operations. Session policies limit the permissions for the role's temporary credential session. The resulting session's permissions are the intersection of the role's identity-based policy and the session policies. You can use the role's temporary credentials in subsequent AWS API calls to access resources in the account that owns the role. You cannot use session policies to grant more permissions than those allowed by the identity-based policy of the role that is being assumed. To learn more about how AWS determines the effective permissions of a role, see [Policy evaluation logic](reference_policies_evaluation-logic.md).

![\[PermissionsWhenPassingRoles_Diagram\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/role_passed_policy_permissions.png)


The policies that are attached to the credentials that made the original call to `AssumeRole` are not evaluated by AWS when making the "allow" or "deny" authorization decision. The user temporarily gives up its original permissions in favor of the permissions assigned by the assumed role. In the case of the `AssumeRoleWithSAML` and `AssumeRoleWithWebIdentity` API operations, there are no policies to evaluate because the caller of the API is not an AWS identity.

## Example: Assigning permissions using AssumeRole


You can use the `AssumeRole` API operation with different kinds of policies. Here are a few examples.

### Role permissions policy


In this example, you call the `AssumeRole` API operation without specifying the session policy in the optional `Policy` parameter. The permissions assigned to the temporary credentials are determined by the permissions policy of the role being assumed. The following example permissions policy grants the role permission to list all objects that are contained in an S3 bucket named `productionapp`. It also allows the role to get, put, and delete objects within that bucket.

**Example role permissions policy**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::productionapp"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::productionapp/*"
    }
  ]
}
```

### Session policy passed as a parameter


Imagine that you want to allow a user to assume the same role as in the previous example. But in this case you want the role session to have permission only to get and put objects in the `productionapp` S3 bucket. You do not want to allow them to delete objects. One way to accomplish this is to create a new role and specify the desired permissions in that role's permissions policy. Another way to accomplish this is to call the `AssumeRole` API and include session policies in the optional `Policy` parameter as part of the API operation. The resulting session's permissions are the intersection of the role's identity-based policies and the session policies. Session policies cannot be used to grant more permissions than those allowed by the identity-based policy of the role that is being assumed. For more information about role session permissions, see [Session policies](access_policies.md#policies_session). 

After you retrieve the new session's temporary credentials, you can pass them to the user that you want to have those permissions.

For example, imagine that the following policy is passed as a parameter of the API call. The person using the session has permissions to perform only these actions: 
+ List all objects in the `productionapp` bucket.
+ Get and put objects in the `productionapp` bucket.

In the following session policy, the `s3:DeleteObject` permission is filtered out and the assumed session is not granted the `s3:DeleteObject` permission. The policy sets the maximum permissions for the role session so that it overrides any existing permissions policies on the role.

**Example session policy passed with `AssumeRole` API call**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::productionapp"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::productionapp/*"
    }
  ]
}
```

### Resource-based policy


Some AWS resources support resource-based policies, and these policies provide another mechanism to define permissions that affect temporary security credentials. Only a few resources, like Amazon S3 buckets, Amazon SNS topics, and Amazon SQS queues support resource-based policies. The following example expands on the previous examples, using an S3 bucket named `productionapp`. The following policy is attached to the bucket. 

When you attach the following resource-based policy to the `productionapp` bucket, *all* users are denied permission to delete objects from the bucket. (See the `Principal` element in the policy.) This includes all assumed role users, even though the role permissions policy grants the `DeleteObject` permission. An explicit `Deny` statement always takes precedence over an `Allow` statement.

**Example bucket policy**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Principal": {"AWS": "*"},
    "Effect": "Deny",
    "Action": "s3:DeleteObject",
    "Resource": "arn:aws:s3:::productionapp/*"
  }
}
```

For more information about how multiple policy types are combined and evaluated by AWS, see [Policy evaluation logic](reference_policies_evaluation-logic.md).

# Monitor and control actions taken with assumed roles
Monitor and control actions taken with assumed roles

An [IAM role](id_roles.md) is an object in IAM that is assigned [permissions](access_policies.md). When you [assume that role](id_roles_manage-assume.md) using an IAM identity or an identity from outside of AWS, you receive a session with the permissions that are assigned to the role. 

When you perform actions in AWS, the information about your session can be logged to AWS CloudTrail for your account administrator to monitor. Administrators can configure roles to require identities to pass a custom string that identifies the person or application that is performing actions in AWS. This identity information is stored as the *source identity* in AWS CloudTrail. When the administrator reviews activity in CloudTrail, they can view the source identity information to determine who or what performed actions with assumed role sessions.

After a source identity is set, it is present in requests for any AWS action taken during the role session. The value that is set persists when a role is used to assume another role through the AWS CLI or AWS API, known as [role chaining](id_roles.md#iam-term-role-chaining). The value that is set cannot be changed during the role session. Administrators can configure granular permissions based on the presence or value of the source identity to further control AWS actions that are taken with shared roles. You can decide whether the source identity attribute can be used, whether it is required, and what value can be used.



The way that you use source identity differs from role session name and session tags in an important way. The source identity value can't be changed after it is set, and it persists for any additional actions that are taken with the role session. Here's how you can use session tags and role session name: 
+ **Session tags** – You can pass session tags when you assume a role or federate a user. Session tags are present when a role is assumed. You can define policies that use tag condition keys to grant permissions to your principals based on their tags. Then you can use CloudTrail to view the requests made to assume roles or federate users. To learn more about session tags, see [Pass session tags in AWS STS](id_session-tags.md).
+ **Role session name** – You can use the `sts:RoleSessionName` condition key in a role trust policy to require that your users provide a specific session name when they assume a role. Role session name can be used to differentiate role sessions when a role is used by different principals. To learn more about role session name, see [sts:RoleSessionName](reference_policies_iam-condition-keys.md#ck_rolesessionname).

We recommend that you use source identity when you want to control the identity that assumes a role. Source identity is also useful for mining CloudTrail logs to determine who used the role to perform actions. 

**Topics**
+ [

## Setting up to use source identity
](#id_credentials_temp_control-access_monitor-setup)
+ [

## Things to know about source identity
](#id_credentials_temp_control-access_monitor-know)
+ [

## Permissions required to set source identity
](#id_credentials_temp_control-access_monitor-perms)
+ [

## Specifying a source identity when assuming a role
](#id_credentials_temp_control-access_monitor-specify-sourceid)
+ [

## Using source identity with AssumeRole
](#id_credentials_temp_control-access_monitor-assume-role)
+ [

## Using source identity with AssumeRoleWithSAML
](#id_credentials_temp_control-access_monitor-assume-role-saml)
+ [

## Using source identity with AssumeRoleWithWebIdentity
](#id_credentials_temp_control-access_monitor-assume-role-web-id)
+ [

## Control access using source identity information
](#id_credentials_temp_control-access_monitor-control-access)
+ [

## Viewing source identity in CloudTrail
](#id_credentials_temp_control-access_monitor-ct)

## Setting up to use source identity
Setting up

The way that you set up to use source identity depends on the method used when your roles are assumed. For example, your IAM users might assume roles directly using the `AssumeRole` operation. If you have enterprise identities, also known as workforce identities, they might access your AWS resources using `AssumeRoleWithSAML`. If end users access your mobile or web applications, they might do so using `AssumeRoleWithWebIdentity`. The following is a high-level workflow overview to help you understand how you can set up to utilize source identity information in your existing environment.

1. **Configure test users and roles** – Using a preproduction environment, configure test users and roles and configure their policies to allow setting a source identity.

   If you use an identity provider (IdP) for your federated identities, configure your IdP to pass a user attribute of your choice for source identity in the assertion or token.

1. **Assume the role** – Test assuming roles and passing a source identity with the users and roles that you set up for testing.

1. **Review CloudTrail** – Review the source identity information for your test roles in your CloudTrail logs.

1. **Train your users** – After you've tested in your preproduction environment, ensure that your users know how to pass in the source identity information, if necessary. Set a deadline for when you will require your users to provide a source identity in your production environment.

1. **Configure production policies** – Configure your policies for your production environment, and then add them to your production users and roles.

1. **Monitor activity** – Monitor your production role activity using CloudTrail logs.

## Things to know about source identity
Things to know

Keep the following in mind when working with source identity.
+ Trust policies for all roles connected to an identity provider (IdP) must have the `sts:SetSourceIdentity` permission. For roles that don't have this permission in the role trust policy, the `AssumeRole*` operation will fail. If you don't want to update the role trust policy for each role, you can use a separate IdP instance for passing source identity. Then add the `sts:SetSourceIdentity` permission to only the roles that are connected to the separate IdP.
+ When an identity sets a source identity, the `sts:SourceIdentity` key is present in the request. For subsequent actions taken during the role session, the `aws:SourceIdentity` key is present in the request. AWS doesn’t control the value of the source identity in either the `sts:SourceIdentity` or `aws:SourceIdentity` keys. If you choose to require a source identity, you must choose an attribute that you want your users or IdP to provide. For security purposes, you must ensure that you can control how those values are provided.
+ The value of source identity must be between 2 and 64 characters long, can contain only alphanumeric characters, underscores, and the following characters: **. , \$1 = @ -** (hyphen). You cannot use a value that begins with the text **aws:**. This prefix is reserved for AWS internal use.
+ The source identity information is not captured by CloudTrail when an AWS service or service-linked role carries out an action on behalf of a federated or workforce identity. 

**Important**  
You cannot switch to a role in the AWS Management Console that requires a source identity to be set when the role is assumed. To assume such a role, you can use the AWS CLI or AWS API to call the `AssumeRole` operation and specify the source identity parameter.

## Permissions required to set source identity
Permissions required to set source identity

In addition to the action that matches the API operation, you must have the following permissions-only action in your policy: 

```
sts:SetSourceIdentity
```
+ To specify a source identity, principals (IAM users and roles) must have permissions to `sts:SetSourceIdentity`. As the administrator, you can configure this in the role trust policy and in the principal’s permissions policy.
+ When you assume a role with another role, called [role chaining](id_roles.md#iam-term-role-chaining), permissions for `sts:SetSourceIdentity` are required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role. Otherwise, the assume role operation will fail.
+ When using source identity, the role trust policies for all roles connected to an IdP must have the `sts:SetSourceIdentity` permission. The `AssumeRole*` operation will fail for any role connected to an IdP without this permission. If you don't want to update the role trust policy for each role, you can use a separate IdP instance for passing source identity and add the `sts:SetSourceIdentity` permission to only the roles that are connected to the separate IdP.
+ To set a source identity across account boundaries, you must include the `sts:SetSourceIdentity` permission in two places. It must be in the permissions policy of the principal in the originating account and in the role trust policy of the role in the target account. You might need to do this, for example, when a role is used to assume a role in another account with [role chaining](id_roles.md#iam-term-role-chaining).

As the account administrator, imagine that you want to allow the IAM user `DevUser` in your account to assume the `Developer_Role` in the same account. But you want to allow this action only if the user has set the source identity to their IAM user name. You can attach the following policy to the IAM user.

**Example identity-based policy attached to DevUser**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AssumeRole",
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": "arn:aws:iam::123456789012:role/Developer_Role"
    },
    {
      "Sid": "SetAwsUserNameAsSourceIdentity",
      "Effect": "Allow",
      "Action": "sts:SetSourceIdentity",
      "Resource": "arn:aws:iam::123456789012:role/Developer_Role",
      "Condition": {
        "StringLike": {
          "sts:SourceIdentity": "${aws:username}"
        }
      }
    }
  ]
}
```

To enforce the acceptable source identity values, you can configure the following role trust policy. The policy gives the IAM user `DevUser` permissions to assume the role and set a source identity. The `sts:SourceIdentity` condition key defines the acceptable source identity value.

**Example role trust policy for source identity**  

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowDevUserAssumeRole",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:user/DevUser"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:SetSourceIdentity"
      ],
      "Condition": {
        "StringEquals": {
          "sts:SourceIdentity": "DevUser"
        }
      }
    }
  ]
}
```

------

Using the credentials for the IAM user `DevUser`, the user attempts to assume the `DeveloperRole` using the following AWS CLI request.

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/Developer_Role \
--role-session-name Dev-project \ 
--source-identity DevUser \
```

When AWS evaluates the request, the request context contains the `sts:SourceIdentity` of `DevUser`.

## Specifying a source identity when assuming a role


You can specify a source identity when you use one of the AWS STS `AssumeRole*` API operations to get temporary security credentials for a role. The API operation that you use differs depending on your use case. For example, if you use IAM roles to give IAM users access to AWS resources that they don’t normally have access to, you might use the `AssumeRole` operation. If you use enterprise identity federation to manage your workforce users, you might use the `AssumeRoleWithSAML` operation. If you use OIDC federation to allow end users to access your mobile or web applications, you might use the `AssumeRoleWithWebIdentity` operation. The following sections explain how to use source identity with each operation. To learn more about common scenarios for temporary credentials, see [Common scenarios for temporary credentials](id_credentials_temp.md#sts-introduction).

## Using source identity with AssumeRole
AssumeRole

The `AssumeRole` operation returns a set of temporary credentials that you can use to access AWS resources. You can use IAM user or role credentials to call `AssumeRole`. To pass source identity while assuming a role, use the `-–source-identity` AWS CLI option or the `SourceIdentity` AWS API parameter. The following example shows how to specify the source identity using the AWS CLI.

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/developer \
--role-session-name Audit \ 
--source-identity Admin \
```

## Using source identity with AssumeRoleWithSAML
AssumeRoleWithSAML

The principal calling the `AssumeRoleWithSAML` operation is authenticated using SAML-based federation. This operation returns a set of temporary credentials that you can use to access AWS resources. For more information about using SAML-based federation for AWS Management Console access, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md). For details about AWS CLI or AWS API access, see [SAML 2.0 federation](id_roles_providers_saml.md). For a tutorial of setting up SAML federation for your Active Directory users, see [AWS Federated Authentication with Active Directory Federation Services (ADFS)](https://aws.amazon.com/blogs/security/aws-federated-authentication-with-active-directory-federation-services-ad-fs/) in the AWS Security Blog. 

As an administrator, you can allow members of your company directory to federate into AWS using the AWS STS `AssumeRoleWithSAML` operation. To do this, you must complete the following tasks:

1. [Configure a SAML provider in your organization](id_roles_providers_saml_3rd-party.md).

1. [Create a SAML provider in IAM](id_roles_providers_create_saml.md).

1. [Configure a role and its permissions in AWS for your SAML federated principals](id_roles_create_for-idp_saml.md).

1. [Finish configuring the SAML IdP and create assertions for the SAML authentication response](id_roles_providers_create_saml_assertions.md).

To set a SAML attribute for source identity, include the `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/SourceIdentity`. Use the `AttributeValue` element to specify the value of the source identity. For example, assume that you want to pass the following identity attribute as the source identity. 

`SourceIdentity:DiegoRamirez`

To pass this attribute, include the following element in your SAML assertion.

**Example snippet of a SAML assertion**  

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/SourceIdentity">
<AttributeValue>DiegoRamirez</AttributeValue>
</Attribute>
```

## Using source identity with AssumeRoleWithWebIdentity
AssumeRoleWithWebIdentity

The principal calling the `AssumeRoleWithWebIdentity` operation is authenticated using OpenID Connect (OIDC)-compliant federation. This operation returns a set of temporary credentials that you can use to access AWS resources. For more information about using OIDC federation for AWS Management Console access, see [OIDC federation](id_roles_providers_oidc.md).

To pass source identity from OpenID Connect (OIDC), you must include the source identity in the JSON Web Token (JWT). Include source identity in the `[https://aws.amazon.com/](https://aws.amazon.com/)source_identity` namespace in the token when you submit the `AssumeRoleWithWebIdentity` request. To learn more about OIDC tokens and claims, see [Using Tokens with User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html) in the *Amazon Cognito Developer Guide*.

For example, the following decoded JWT is a token that is used to call `AssumeRoleWithWebIdentity` with the `Admin` source identity.

**Example decoded JSON Web Token**  

```
{
    "sub": "john",
    "aud": "ac_oic_client",
    "jti": "ZYUCeRMQVtqHypVPWAN3VB",
    "iss": "https://xyz.com",
    "iat": 1566583294,
    "exp": 1566583354,
    "auth_time": 1566583292,
    "https://aws.amazon.com/source_identity":"Admin"
}
```

## Control access using source identity information
Control access using source identity

When a source identity is initially set, the [sts:SourceIdentity](reference_policies_iam-condition-keys.md#ck_sourceidentity) key is present in the request. After a source identity is set, the [aws:SourceIdentity](reference_policies_condition-keys.md#condition-keys-sourceidentity) key is present in all subsequent requests made during the role session. As the administrator, you can write policies that grant conditional authorization to perform AWS actions based on the existence or value of the source identity attribute.

Imagine that you want to require your developers to set a source identity to assume a critical role that has permission to write to a production critical AWS resource. Also imagine that you grant AWS access to your workforce identities using `AssumeRoleWithSAML`. You only want senior developers Saanvi and Diego to have access to the role, so you create the following trust policy for the role.

**Example role trust policy for source identity (SAML)**  

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "SAMLProviderAssumeRoleWithSAML",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::111122223333:saml-provider/name-of-identity-provider"
      },
      "Action": [
        "sts:AssumeRoleWithSAML"
      ],
      "Condition": {
        "StringEquals": {
          "SAML:aud": "https://signin.aws.amazon.com/saml"
        }
      }
    },
    {
      "Sid": "SetSourceIdentitySrEngs",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::111122223333:saml-provider/name-of-identity-provider"
      },
      "Action": [
        "sts:SetSourceIdentity"
      ],
      "Condition": {
        "StringLike": {
          "sts:SourceIdentity": [
            "Saanvi",
            "Diego"
          ]
        }
      }
    }
  ]
}
```

------

The trust policy contains a condition for `sts:SourceIdentity` that requires a source identity of Saanvi or Diego to assume the critical role.

Alternatively, if you use an OIDC provider for federation and users are authenticated with `AssumeRoleWithWebIdentity`, your role trust policy might look as follows.

**Example role trust policy for source identity (OIDC provider)**  

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::111122223333:oidc-provider/server.example.com"
      },
      "Action": [
        "sts:AssumeRoleWithWebIdentity",
        "sts:SetSourceIdentity"
      ],
      "Condition": {
        "StringEquals": {
          "server.example.com:aud": "oidc-audience-id"
        },
        "StringLike": {
          "sts:SourceIdentity": [
            "Saanvi",
            "Diego"
          ]
        }
      }
    }
  ]
}
```

------

### Role chaining and cross-account requirements


Imagine that you want to allow users who have assumed `CriticalRole` to assume a `CriticalRole_2` in another account. The role session credentials that were obtained to assume `CriticalRole` are used to [role chain](id_roles.md#iam-term-role-chaining) to a second role, `CriticalRole_2`, in a different account. The role is being assumed across an account boundary. Therefore, the `sts:SetSourceIdentity` permission must be granted in both the permissions policy on `CriticalRole` and in the role trust policy on `CriticalRole_2`.

**Example permissions policy on CriticalRole**  

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AssumeRoleAndSetSourceIdentity",
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole",
        "sts:SetSourceIdentity"
      ],
      "Resource": "arn:aws:iam::222222222222:role/CriticalRole_2"
    }
  ]
}
```

------

To secure setting source identity across the account boundary, the following role trust policy trusts only the role principal for `CriticalRole` to set the source identity.

**Example role trust policy on CriticalRole\$12**  

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111111111111:role/CriticalRole"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:SetSourceIdentity"
      ],
      "Condition": {
        "StringLike": {
          "aws:SourceIdentity": ["Saanvi","Diego"]
        }
      }
    }
  ]
}
```

------

The user makes the following call using role session credentials obtained from assuming CriticalRole. The source identity was set during the assumption of CriticalRole, so it does not need to be explicitly set again. If the user attempts to set a source identity that is different from the value set when `CriticalRole` was assumed, the assume role request will be denied.

**Example AssumeRole CLI request**  

```
aws sts assume-role \ 
--role-arn arn:aws:iam::222222222222:role/CriticalRole_2 \
--role-session-name Audit \
```

When the calling principal assumes the role, the source identity in the request persists from the first assumed role session. Therefore, both the `aws:SourceIdentity` and `sts:SourceIdentity` keys are present in the request context.

## Viewing source identity in CloudTrail
Viewing source identity in AWS CloudTrail

You can use CloudTrail to view the requests made to assume roles or federate users. You can also view the role or user requests to take actions in AWS. The CloudTrail log file includes information about the source identity set for the assumed-role or federated user session. For more information, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md)

For example, assume that a user makes an AWS STS `AssumeRole` request, and sets a source identity. You can find the `sourceIdentity` information in the `requestParameters` key in your CloudTrail log.

**Example requestParameters section in an AWS CloudTrail log**  

```
"eventVersion": "1.05",
    "userIdentity": {
        "type": "AWSAccount",
        "principalId": "AIDAJ45Q7YFFAREXAMPLE",
        "accountId": "111122223333"
    },
    "eventTime": "2020-04-02T18:20:53Z",
    "eventSource": "sts.amazonaws.com",
    "eventName": "AssumeRole",
    "awsRegion": "us-east-1",
    "sourceIPAddress": "203.0.113.64",
    "userAgent": "aws-cli/1.16.96 Python/3.6.0 Windows/10 botocore/1.12.86",
    "requestParameters": {
        "roleArn": "arn:aws:iam::123456789012:role/DevRole",
        "roleSessionName": "Dev1",
        "sourceIdentity": "source-identity-value-set"
    }
```

If the user uses the assumed role session to perform an action, the source identity information is present in the `userIdentity` key in the CloudTrail log.

**Example userIdentity key in an AWS CloudTrail log**  

```
{
  "eventVersion": "1.08",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROAJ45Q7YFFAREXAMPLE:Dev1",
    "arn": "arn:aws:sts::123456789012:assumed-role/DevRole/Dev1",
    "accountId": "123456789012",
    "accessKeyId": "ASIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROAJ45Q7YFFAREXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/DevRole",
        "accountId": "123456789012",
        "userName": "DevRole"
      },
      "webIdFederationData": {},
      "attributes": {
        "mfaAuthenticated": "false",
        "creationDate": "2021-02-21T23:46:28Z"
      },
      "sourceIdentity": "source-identity-value-present"
    }
  }
}
```

To see example AWS STS API events in CloudTrail logs, see [Example IAM API events in CloudTrail log](cloudtrail-integration.md#cloudtrail-integration_examples-iam-api). For more details about the information contained in CloudTrail log files, see [CloudTrail Event Reference](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/eventreference.html) in the *AWS CloudTrail User Guide*.

# Permissions for GetFederationToken


The `GetFederationToken` operation is called by an IAM user and returns temporary credentials for that user. This operation *federates* the user. The permissions assigned to an AWS STS federated user session are defined in one of two places: 
+ The session policies passed as a parameter of the `GetFederationToken` API call. (This is most common.)
+ A resource-based policy that explicitly names the AWS STS federated user session in the `Principal` element of the policy. (This is less common.)

Session policies are advanced policies that you pass as parameters when you programmatically create a temporary session. When you create an AWS STS federated user session and pass session policies, the resulting session's permissions are the intersection of the user's identity-based policy and the session policies. You cannot use the session policy to grant more permissions than those allowed by the identity-based policy of the user that is being federated.

In most cases if you do not pass a policy with the `GetFederationToken` API call, the resulting temporary security credentials have no permissions. However, a resource-based policy can provide additional permissions for the session. You can access a resource with a resource-based policy that specifies your session as the allowed principal. 

The following figures show a visual representation of how the policies interact to determine permissions for the temporary security credentials returned by a call to `GetFederationToken`.

![\[IAM userThe following illustrations show check marks to indicate that session permissions are the intersection of the user's identity-based policy and the session policies. Session permissions can also be the intersection of the user's identity-based policy and resource-based policies.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/getfederationtoken-permissions.diagram.png)


## Example: Assigning permissions using GetFederationToken


You can use the `GetFederationToken` API action with different kinds of policies. Here are a few examples.

### Policy attached to the IAM user


In this example, you have a browser-based client application that relies on two backend web services. One backend service is your own authentication server that uses your own identity system to authenticate the client application. The other backend service is an AWS service that provides some of the client application's functionality. The client application is authenticated by your server, and your server creates or retrieves the appropriate permissions policy. Your server then calls the `GetFederationToken` API to obtain temporary security credentials, and returns those credentials to the client application. The client application can then make requests directly to the AWS service with the temporary security credentials. This architecture allows the client application to make AWS requests without embedding long-term AWS credentials.

Your authentication server calls the `GetFederationToken` API with the long-term security credentials of an IAM user named `token-app`. But the long-term IAM user credentials remain on your server and are never distributed to the client. The following example policy is attached to the `token-app` IAM user and defines the broadest set of permissions that your AWS STS federated users (clients) will need. Note that the `sts:GetFederationToken` permission is required for your authentication service to obtain temporary security credentials for the AWS STS federated users.

**Example policy attached to IAM user `token-app` that calls `GetFederationToken`**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sts:GetFederationToken",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "dynamodb:ListTables",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "sqs:ReceiveMessage",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "sns:ListSubscriptions",
      "Resource": "*"
    }
  ]
}
```

The preceding policy grants several permissions to the IAM user. However, this policy alone doesn't grant any permissions to the AWS STS federated user. If this IAM user calls `GetFederationToken` and does not pass a policy as a parameter of the API call, the resulting AWS STS federated user has no effective permissions. 

### Session policy passed as parameter


The most common way to ensure that the AWS STS federated user is assigned appropriate permission is to pass session policies in the `GetFederationToken` API call. Expanding on the previous example, imagine that `GetFederationToken` is called with the credentials of the IAM user `token-app`. Then imagine that the following session policy is passed as a parameter of the API call. The resulting AWS STS federated user has permission to list the contents of the Amazon S3 bucket named `productionapp`. The user can't perform the Amazon S3 `GetObject`, `PutObject`, and `DeleteObject` actions on items in the `productionapp` bucket.

The federated user is assigned these permissions because the permissions are the intersection of the IAM user policies and the session policies that you pass.

The AWS STS federated user could not perform actions in Amazon SNS, Amazon SQS, Amazon DynamoDB, or in any S3 bucket except `productionapp`. These actions are denied even though those permissions are granted to the IAM user that is associated with the `GetFederationToken` call.

**Example session policy passed as parameter of `GetFederationToken` API call**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::productionapp"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": ["arn:aws:s3:::productionapp/*"]
    }
  ]
}
```

### Resource-based policies


Some AWS resources support resource-based policies, and these policies provide another mechanism to grant permissions directly to an AWS STS federated user. Only some AWS services support resource-based policies. For example, Amazon S3 has buckets, Amazon SNS has topics, and Amazon SQS has queues that you can attach policies to. For a list of all services that support resource-based policies, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) and review the "Resource-based policies" column of the tables. You can use resource-based policies to assign permissions directly to an AWS STS federated user. Do this by specifying the Amazon Resource Name (ARN) of the AWS STS federated user in the `Principal` element of the resource-based policy. The following example illustrates this and expands on the previous examples, using an S3 bucket named `productionapp`. 

The following resource-based policy is attached to the bucket. This bucket policy allows an AWS STS federated user named Carol to access the bucket. When the example policy described earlier is attached to the `token-app` IAM user, the AWS STS federated user named Carol has permission to perform the `s3:GetObject`, `s3:PutObject`, and `s3:DeleteObject` actions on the bucket named `productionapp`. This is true even when no session policy is passed as a parameter of the `GetFederationToken` API call. That's because in this case the AWS STS federated user named Carol has been explicitly granted permissions by the following resource-based policy. 

Remember, an AWS STS federated user is granted permissions only when those permissions are explicitly granted to both the IAM user ***and*** the AWS STS federated user. They can also be granted (within the account) by a resource-based policy that explicitly names the AWS STS federated user in the `Principal` element of the policy, as in the following example.

**Example bucket policy that allows access to federated user**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Principal": {
            "AWS": "arn:aws:sts::111122223333:federated-user/Carol"
        },
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:PutObject",
            "s3:DeleteObject"
        ],
        "Resource": [
            "arn:aws:s3:::productionapp/*"
        ]
    }
}
```

For more information about how policies are evaluated see [Policy evaluation logic](reference_policies_evaluation-logic.md).

# Permissions for GetSessionToken


The primary occasion for calling the `GetSessionToken` API operation or the `get-session-token` CLI command is when a user must be authenticated with multi-factor authentication (MFA). It is possible to write a policy that allows certain actions only when those actions are requested by a user who has been authenticated with MFA. In order to successfully pass the MFA authorization check, a user must first call `GetSessionToken` and include the optional `SerialNumber` and `TokenCode` parameters. If the user is successfully authenticated with an MFA device, the credentials returned by the `GetSessionToken` API operation include the MFA context. This context indicates that the user is authenticated with MFA and is authorized for API operations that require MFA authentication.

## Permissions required for GetSessionToken


No permissions are required for a user to get a session token. The purpose of the `GetSessionToken` operation is to authenticate the user using MFA. You cannot use policies to control authentication operations.

To grant permissions to perform most AWS operations, you add the action with the same name to a policy. For example, to create a user, you must use the `CreateUser` API operation, the `create-user` CLI command, or the AWS Management Console. To perform these operations, you must have a policy that allows you to access the `CreateUser` action.

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

****  

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

------

You can include the `GetSessionToken` action in your policies, but it has no effect on a user's ability to perform the `GetSessionToken` operation.

## Permissions granted by GetSessionToken


If `GetSessionToken` is called with the credentials of an IAM user, the temporary security credentials have the same permissions as the IAM user. Similarly, if `GetSessionToken` is called with AWS account root user credentials, the temporary security credentials have root user permissions.

**Note**  
We recommend that you do not call `GetSessionToken` with root user credentials. Instead, follow our [best practices](best-practices-use-cases.md) and create IAM users with the permissions they need. Then use these IAM users for everyday interaction with AWS.

The temporary credentials that you get when you call `GetSessionToken` have the following capabilities and limitations:
+ You can use the credentials to access the AWS Management Console by passing the credentials to the federation single sign-on endpoint at `https://signin.aws.amazon.com/federation`. For more information, see [Enable custom identity broker access to the AWS console](id_roles_providers_enable-console-custom-url.md).
+ You **cannot** use the credentials to call IAM or AWS STS API operations. You **can** use them to call API operations for other AWS services.

Compare this API operation and its limitations and capability with the other API operations that create temporary security credentials at [Compare AWS STS credentials](id_credentials_sts-comparison.md)

For more information about MFA-protected API access using `GetSessionToken`, see [Secure API access with MFA](id_credentials_mfa_configure-api-require.md).

# Disabling permissions for temporary security credentials
Disabling permissions

Temporary security credentials are valid until they expire. These credentials are valid for the specified duration, from 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 hours). The default session duration is 43,200 seconds (12 hours). You can revoke these credentials, but you must also change permissions for the IAM user or role to stop the use of compromised credentials for malicious account activity. Permissions assigned to temporary security credentials are evaluated each time they are used to make an AWS request. Once you remove all permissions from the credentials, AWS requests that use them fail.

It might take a few minutes for policy updates to take effect. For IAM role sessions, you can revoke the role’s temporary security credentials to force all users assuming the role to reauthenticate and request new credentials. For more information, see [Revoke the role’s temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_revoke-sessions.html).

You cannot change the permissions for an AWS account root user. Likewise, you cannot change the permissions for the temporary security credentials that were created by calling `GetFederationToken` or `GetSessionToken` while signed in as the root user. For this reason, we recommend that you do not call `GetFederationToken` or `GetSessionToken` as a root user.

For procedures on how to change the permissions for an IAM user, see [Change permissions for an IAM user](id_users_change-permissions.md).

For procedures on how to change the permissions for an IAM role, see [Update permissions for a role](id_roles_update-role-permissions.md).

**Important**  
You can't edit roles in IAM that were created from IAM Identity Center permission sets. You must revoke the active permission set session for a user in IAM Identity Center. For more information, see [Revoke active IAM role sessions created by permission sets](https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#revoke-user-permissions) in the *IAM Identity Center User Guide*.

**Topics**
+ [

## Deny access to all IAM role sessions associated with a role
](#deny-access-to-all-sessions)
+ [

## Deny access to a specific IAM role session
](#deny-access-to-specific-session)
+ [

## Deny access to temporary security credentials sessions with condition context keys
](#deny-access-to-specific-session-condition-key)
+ [

## Deny access to a specific principal with resource-based policies
](#deny-access-with-resource-based)

## Deny access to all IAM role sessions associated with a role


This procedure denies permissions to **all** IAM role sessions associated with a role. Use this approach when you are concerned about suspicious access by:


+ Principals from another account using cross-account access
+ External user identities with permissions to access AWS resources in your account
+ Users who have been authenticated in a mobile or web application with an OIDC provider

To change or remove the permissions assigned to the temporary security credentials obtained by calling `AssumeRole`, `AssumeRoleWithSAML`, or `AssumeRoleWithWebIdentity`, `GetFederationToken`, or `GetSessionToken`, you can edit or delete the identity-based policy that defines the permissions for the role.

**Important**  
If there's a resource-based policy that allows the principal access, you must also add an explicit deny for that resource. See [Deny access to a specific principal with resource-based policies](#deny-access-with-resource-based) for details.

**To deny access to **all** IAM role sessions associated with a role**

1. Sign in to the AWS Management Console and open the IAM console.

1. In the navigation pane, choose **Roles**..

1. Choose the name of the role to edit. You can use the search box to filter the list.

1. Choose the **Permissions** tab.

1. Select the relevant policy to edit. Before you edit a customer managed policy, review the **Entities attached** tab to avoid disrupting access to other identities that may have the same policy attached.

1. Choose the **JSON** tab and update the policy to deny all resources and actions.
**Note**  
These permissions are the same as those in the AWS managed policy [AWSDenyAll](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSDenyAll.html). You can attach this AWS managed policy to any IAM user or role you want to deny all access to.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "DenyAll",
               "Effect": "Deny",
               "Action": [
                   "*"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

1. On the **Review** page, review the policy **Summary** and then choose **Save changes** to save your work.

When you update the policy, the changes affect the permissions of all temporary security credentials associated with the role, including credentials that were issued before you changed the role's permissions policy. 

After you update the policy, you can [revoke the role’s temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_revoke-sessions.html) to immediately revoke all permissions to the role's issued credentials.

## Deny access to a specific IAM role session


When you update IAM roles with a deny-all policy or delete the role entirely, all users that have access to the role are disrupted. You can deny access without impacting the permissions of all other sessions associated with the role.

The `Principal` can be denied permissions using [condition context keys](#deny-access-to-specific-session-condition-key) or [resource-based policies](#deny-access-with-resource-based).

**Tip**  
You can find the ARNs of federated users using AWS CloudTrail logs. For more information, see [How to Easily Identify Your Federated Users by Using AWS CloudTrail](https://aws.amazon.com/blogs/security/how-to-easily-identify-your-federated-users-by-using-aws-cloudtrail/).

## Deny access to temporary security credentials sessions with condition context keys


You can use condition context keys in identity-based policies in situations where you want to deny access to specific temporary security credential sessions without affecting the permissions of the IAM user or role that created the credentials. For IAM roles, after you update the policy, you can also [revoke the role’s temporary security credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_revoke-sessions.html) sessions to immediately revoke all issued credentials.

For more information about condition context keys, see [AWS global condition context keys](reference_policies_condition-keys.md).

### aws:PrincipalArn


You can use condition context key [aws:PrincipalArn](reference_policies_condition-keys.md#condition-keys-principalarn) in an identity-based policy to deny access to a specific principal by their Amazon Resource Name (ARN). You do this by specifying the ARN of the IAM user, role, or AWS STS federated user session the temporary security credentials are associated with in the Condition element of a policy.

**To deny access to a specific principal by their ARN**

1. In the IAM console navigation pane, choose **Users** or **Roles**.

1. Choose the name of the IAM user or role to edit. You can use the search box to filter the list.

1. Choose the **Permissions** tab.

1. Select the relevant policy to edit. Before you edit a customer managed policy, review the **Entities attached** tab to avoid disrupting access to other identities that may have the same policy attached.

1. Choose the **JSON** tab and add a deny statement for the principal ARN as shown in the following example.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
           "ArnEquals": {
             "aws:PrincipalArn": [
               "arn:aws:iam::222222222222:role/ROLENAME",
               "arn:aws:iam::222222222222:user/USERNAME",
               "arn:aws:iam::222222222222:federated-user/USERNAME" 
             ]
           }
         }
       }
     ]
   }
   ```

------

1. On the **Review** page, review the policy **Summary** and then choose **Save changes** to save your work.

### aws:SourceIdentity


You can use condition context key [aws:SourceIdentity](reference_policies_condition-keys.md#condition-keys-sourceidentity) in an identity-based policy to deny access to a specific source identity associated with an IAM role session. This applies as long as the role session was issued by setting the `SourceIdentity` request parameter when the principal assumed a role using any AWS STS `assume-role`\$1 CLI commands, or AWS STS `AssumeRole`\$1 API operations. You do this by specifying the source identity that the temporary security credentials are associated with in the `Condition` element of a policy. 

Unlike context key [sts:RoleSessionName](reference_policies_iam-condition-keys.md#ck_rolesessionname), after the source identity is set, the value cannot be changed. The `aws:SourceIdentity` key is present in the request context for all actions taken by the role. The source identity persists into subsequent role sessions when you use the session credentials to assume another role. Assuming one role from another is called [role chaining](id_roles.md#iam-term-role-chaining).

The following policy shows an example of how you can deny access to temporary security credential sessions using condition context key `aws:SourceIdentity`. If you specify the source identity associated with a role session, it will deny role sessions with the named source identity without affecting the permissions of the role that created the credentials. For this example, the source identity set by the principal when the role session was issued is `nikki_wolf@example.com`. Any request made by a role session with the source identity `nikki_wolf@example.com` will be denied because the source identity is included in the policy condition and the policy Effect is set to `Deny`.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "StringLike": {
          "aws:SourceIdentity": [
            "nikki_wolf@example.com",
            "<source identity value>"
          ]
        }
      }
    }
  ]
}
```

------

### aws:userid


You can use condition context key [aws:userid](reference_policies_condition-keys.md#condition-keys-userid) in an identity-based policy to deny access to all or specific temporary security credential sessions associated with the IAM user or role. You do this by specifying the unique identifier (ID) of the IAM user, role, or AWS STS federated user session the temporary security credentials are associated with in the `Condition` element of a policy.

The following policy shows an example of how you can deny access to temporary security credential sessions using condition context key `aws:userid`.
+ `AIDAXUSER1` represents the unique ID for an IAM user. Specifying the unique ID of an IAM user as a value for context key `aws:userid` will deny access to the IAM user. This includes any temporary security credential sessions that were created by calling the `GetSessionToken` API.
+ `AROAXROLE1:*` represents the unique ID for all sessions associated with the IAM role. Specifying the unique ID of an IAM role and a wildcard (\$1) character in the caller-specified-role-session-name portion as a value for context key `aws:userid` will deny all sessions associated with the role.
+ `AROAXROLE2:<caller-specified-role-session-name>` represents the unique ID for an assumed-role session. In the caller-specified-role-session-name portion of the assumed-role unique ID you can specify a role session name or a wildcard character if the StringLike condition operator is used. If you specify the role session name, it will deny the named role session without affecting the permissions of the role that created the credentials. If you specify a wildcard character for the role session name, it will deny all sessions associated with the role.
**Note**  
The caller-specified role session name, which is part of the unique identifier for an assumed-role session, can change during role chaining. Role chaining occurs when one role assumes another role. The role session name is set using the `RoleSessionName` request parameter when the principal assumes a role using the AWS STS `AssumeRole` API operation.
+ `account-id:<federated-user-caller-specified-name>` represents the unique ID for an AWS STS federated user session. An IAM user creates this session by calling the `GetFederationToken` API. Specifying the unique ID for an AWS STS federated user session denies the named federated session without affecting the permissions of the IAM user that created the credentials.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "StringLike": {
          "aws:userId": [
            "AIDAXUSER1",
            "AROAXROLE1:*",
            "AROAXROLE2:<caller-specified-role-session-name>",
            "123456789012:<federated-user-caller-specified-name>"
          ]
        }
      }
    }
  ]
}
```

------

For specific examples of principal key values, see [Principal key values](reference_policies_variables.md#principaltable). For information about IAM unique identifiers and how to get them, see [Unique identifiers](reference_identifiers.md#identifiers-unique-ids).

## Deny access to a specific principal with resource-based policies


To restrict access to a specific principal with a resource-based policy, you can use condition context keys [aws:PrincipalArn](reference_policies_condition-keys.md#condition-keys-principalarn) or [aws:SourceIdentity](reference_policies_condition-keys.md#condition-keys-sourceidentity) in the `Condition` element. A resource-based policy is a permission policy attached to a resource and controls who can access the resource and what actions they can perform on it. 

When you use the `aws:PrincipalARN` context key, specify the ARN of the IAM user, role, or AWS STS federated user session associated with the temporary security credentials in the Condition element of a policy. The following example policy demonstrates how to use the `aws:PrincipalARN` context key in a resource-based policy:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Principal": "*",
    "Effect": "Deny",
    "Action": "s3:*",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
    "Condition": {
      "ArnEquals": {
        "aws:PrincipalArn": [
          "arn:aws:iam::222222222222:role/ROLENAME",
          "arn:aws:iam::222222222222:user/USERNAME",
          "arn:aws:sts::222222222222:federated-user/USERNAME"
        ]
      }
    }
  }
}
```

------

When you use the `aws:SourceIdentity` context key, specify the source identity value associated with the role's temporary security credentials in the `Condition` element of a policy. This applies as long as the role session was issued by setting the `SourceIdentity` request parameter when the principal assumed a role using any AWS STS `assume-role`\$1 CLI commands, or AWS STS `AssumeRole`\$1 API operations. The following example demonstrates how to use the `aws:SourceIdentity` context key in a resource-based policy:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Principal": "*",
    "Effect": "Deny",
    "Action": "s3:*",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
    "Condition": {
      "StringLike": {
        "aws:SourceIdentity": [
          "nikki_wolf@example.com",
          "<source identity value>"
        ]
      }
    }
  }
}
```

------

If you only update the identity-based policy for a principal, they can still perform actions allowed in the resource-based policy, except when those actions are explicitly denied in the identity-based policy.

**To deny access to a specific principal in a resource-based policy**

1. Refer to [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md) to see if the service supports resource-based policies.

1. Sign in to the AWS Management Console and open the console for the service. Each service has a different location in the console for attaching policies.

1. Edit the resource-based policy. Add a deny policy statement to specify the identifying information of the credential:

   1. In the `Principal` element, enter wildcard (\$1). The principal will be restricted in the `Condition` element.

   1. In the `Effect` element, enter “Deny.”

   1. In `Action`, enter the service namespace and the name of the action to deny. To deny all actions, use the wildcard (\$1) character. For example: `"s3:*"`.

   1. In the `Resource` element, enter the ARN of the target resource. For example: `"arn:aws:s3:::amzn-s3-demo-bucket"`.

   1. In the `Condition` element, specify either the `aws:PrincipalARN` or `aws:SourceIdentity` context key.

      If you use the `aws:PrincipalARN` context key, enter the ARN of the principal to deny access for.

      If you use the `aws:SourceIdentity` context key, enter the source identity value set in the role session to deny access for.

1. Save your work.

# Granting permissions to create temporary security credentials
Granting permissions to create credentials

By default, IAM users do not have permission to create temporary security credentials for AWS STS federated user sessions and roles. You must use a policy to provide your users with these permissions. Although you can grant permissions directly to a user, we strongly recommend that you grant permissions to a group. This makes management of the permissions much easier. When someone no longer needs to perform the tasks associated with the permissions, you simply remove them from the group. If someone else needs to perform that task, add them to the group to grant the permissions.

To grant an IAM group permission to create temporary security credentials for AWS STS federated user sessions or roles, you attach a policy that grants one or both of the following privileges:
+ For OIDC and SAML federated principals to access an IAM role, grant access to AWS STS `AssumeRole`.
+ <a name="para_gsy_hxg_1t"></a>For AWS STS federated users that don't need a role, grant access to AWS STS `GetFederationToken`.

 For more information about the differences between the `AssumeRole` and `GetFederationToken` API operations, see [Request temporary security credentials](id_credentials_temp_request.md).

IAM users can also call [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) to create temporary security credentials. No permissions are required for a user to call `GetSessionToken`. The purpose of this operation is to authenticate the user using MFA. You cannot use policies to control authentication. This means that you cannot prevent IAM users from calling `GetSessionToken` to create temporary credentials.

**Example policy that grants permission to assume a role**  
The following example policy grants permission to call `AssumeRole` for the `UpdateApp` role in AWS account `123123123123`. When `AssumeRole` is used, the user (or application) that creates the security credentials on behalf of a federated user cannot delegate any permissions that are not already specified in the role permission policy.     
****  

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

**Example policy that grants permission to create temporary security credentials for a federated user**  
The following example policy grants permission to access `GetFederationToken`.    
****  

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

**Important**  
When you give IAM users permission to create temporary security credentials for AWS STS federated users with `GetFederationToken`, be aware that this permits those users to delegate their own permissions. For more information about delegating permissions across IAM users and AWS accounts, see [Examples of policies for delegating access](id_roles_create_policy-examples.md). For more information about controlling permissions in temporary security credentials, see [Permissions for temporary security credentials](id_credentials_temp_control-access.md). 

**Example policy that grants a user limited permission to create temporary security credentials for federated users**  
When you let an IAM user call `GetFederationToken`, it is a best practice to restrict the permissions that the IAM user can delegate. For example, the following policy shows how to let an IAM user create temporary security credentials only for AWS STS federated users whose names start with *Manager*.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [{
    "Effect": "Allow",
    "Action": "sts:GetFederationToken",
    "Resource": ["arn:aws:sts::123456789012:federated-user/Manager*"]
  }]
}
```

# Granting permissions to use identity-enhanced console sessions
Granting permissions to use identity-enhanced console sessions

Identity-enhanced console sessions enables AWS IAM Identity Center user and session IDs to be included in users' AWS console sessions when they sign in. For example, Amazon Q Developer Pro uses identity-enhanced console sessions to personalize the service experience. For more information about identity-enhanced console sessions, see [Enabling identity-enhanced console sessions](https://docs.aws.amazon.com/singlesignon/latest/userguide/identity-enhanced-sessions.html) in the *AWS IAM Identity Center User Guide*. For information about Amazon Q Developer setup, see [Setting up Amazon Q Developer](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/setting-up.html) in the *Amazon Q Developer User Guide*.

For identity-enhanced console sessions to be available to a user, you must use an identity-based policy to grant the IAM principal the `sts:SetContext` permission for the resource that represents their own console session. 

**Important**  
By default, users do not have permission to set context for their identity-enhanced console sessions. To allow this, you must grant the IAM principal the `sts:SetContext` permission in an identity-based policy as shown in the policy example below.

The following example identity-based policy grants the `sts:SetContext` permission to an IAM principal, allowing the principal to set identity-enhanced console session context for their own AWS console sessions. The policy resource, `arn:aws:sts::account-id:self`, represents the caller’s AWS session. The `account-id` ARN segment can be replaced with a wildcard character `*` in cases where the same permission policy is deployed across multiple accounts, such as when this policy is deployed using IAM Identity Center permission sets.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:SetContext",
            "Resource": "arn:aws:sts::111122223333:self"
        }
    ]
}
```

------

# Manage AWS STS in an AWS Region


A Regional endpoint is the URL of the entry point within a particular region for an AWS web service. AWS recommends using Regional AWS Security Token Service (AWS STS) endpoints instead of the global endpoint to reduce latency, build in redundancy, and increase session token validity. Although the global (legacy) AWS STS endpoint `https://sts.amazonaws.com` is highly available, it’s hosted in a single AWS Region, US East (N. Virginia), and like other endpoints, it doesn’t provide automatic failover to endpoints in other Regions.
+ **Reduce latency** – By making your AWS STS calls to an endpoint that is geographically closer to your services and applications, you can access AWS STS services with lower latency and better response times.
+ **Build in redundancy** – You can limit the effects of a failure within a workload to a limited number of components with a predictable scope of impact containment. Using regional AWS STS endpoints lets you align the scope of your components with the scope of your session tokens. For more information about this reliability pillar, see [Use fault isolation to protect your workload](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/use-fault-isolation-to-protect-your-workload.html) in the *AWS Well-Architected Framework*.
+ **Increase session token validity** – Session tokens from Regional AWS STS endpoints are valid in all AWS Regions. Session tokens from the global STS endpoint are valid only in AWS Regions that are enabled by default. If you intend to enable a new Region for your account, you can use session tokens from Regional AWS STS endpoints. If you choose to use the global endpoint, you must change the Region compatibility of AWS STS session tokens for the global endpoint. Doing so ensures that tokens are valid in all AWS Regions.

For a list of AWS STS Regions and their endpoints, see [AWS STS Regions and endpoints](id_credentials_temp_region-endpoints.md).

**Note**  
AWS has made changes to the AWS Security Token Service (AWS STS) global endpoint (`https://sts.amazonaws.com`) in Regions [enabled by default](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) to enhance its resiliency and performance. AWS STS requests to the global endpoint are automatically served in the same AWS Region as your workloads. These changes will not be deployed to opt-in Regions. We recommend that you use the appropriate AWS STS regional endpoints. For more information, see [AWS STS global endpoint changes](id_credentials_temp_region-endpoints.md#reference_sts_global_endpoint_changes).

**Topics**
+ [

## Activating and deactivating AWS STS in an AWS Region
](#sts-regions-activate-deactivate)
+ [

## Writing code to use AWS STS Regions
](#id_credentials_temp_enable-regions_writing_code)
+ [

## Managing global endpoint session tokens
](#sts-regions-manage-tokens)

## Activating and deactivating AWS STS in an AWS Region


When you activate AWS STS endpoints for a Region, AWS STS can issue temporary credentials to users and roles in your account that make an AWS STS request. Those credentials can then be used in any Region that is enabled by default or is manually enabled. For Regions that are enabled by default, you must activate the Regional AWS STS endpoint in the account where the temporary credentials are generated. It does not matter whether a user is signed into the same account or a different account when they make the request. When requesting temporary credentials for a role in another AWS account using a Region that is manually enabled, the target account (the account containing the role) must enable that Region for AWS STS operations. This ensures that the temporary security credentials can be generated correctly.

For example, imagine a user in account A wants to send an `sts:AssumeRole` API request to the [AWS STS Regional endpoint](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_region-endpoints.html) `https://sts.ap-southeast-3.amazonaws.com`. The request is for temporary credentials for the role named `Developer` in account B. Because the request is to create credentials for an entity in account B, account B must have the `ap-southeast-3` Region enabled. Users from account A (or any other account) can call the `ap-southeast-3` AWS STS endpoint to request credentials for account B whether or not the Region is activated in their accounts. To learn more, see [Enable or disable AWS Regions in your account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html).

**Note**  
Active Regions are available to everyone that uses temporary credentials in that account. To control which IAM users or roles can access the Region, use the `aws:RequestedRegion` condition key in your permissions policies.

**To activate or deactivate AWS STS in a Region that is enabled by default (console)**

1. Sign in as a root user or a user with permissions to perform IAM administration tasks.

1. Open the [IAM console](https://console.aws.amazon.com/iam/home?#home) and in the navigation pane choose [https://console.aws.amazon.com/iam/home?#account_settings](https://console.aws.amazon.com/iam/home?#account_settings).

1. In the **Security Token Service (STS)** section **Endpoints**, find the Region that you want to configure, and then choose **Active** or **Inactive** in the **STS status** column.

1. In the dialog box that opens, choose **Activate** or **Deactivate**.

For Regions that must be enabled, we activate AWS STS automatically when you enable the Region. After you enable a Region, AWS STS is always active for the Region and you cannot deactivate it. To learn about enabling Regions that are disabled by default, see [ Specifying which AWS Regions your account can use](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) in the *AWS Account Management Reference Guide*.

## Writing code to use AWS STS Regions


After you activate a Region, you can direct AWS STS API calls to that Region. The following Java code snippet demonstrates how to configure an `AWSSecurityTokenService` object to make requests to the Europe (Milan) (eu-south-1) Region.

```
EndpointConfiguration regionEndpointConfig = new EndpointConfiguration("https://sts.eu-south-1.amazonaws.com", "eu-south-1");
AWSSecurityTokenService stsRegionalClient = AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(credentials)
.withEndpointConfiguration(regionEndpointConfig)
.build();
```

AWS STS recommends that you make calls to a Regional endpoint. To learn how to manually enable a Region, see [Specify which AWS Regions your account can use](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) in the *AWS Account Management Reference Guide*.

In the example, the first line instantiates an `EndpointConfiguration` object called `regionEndpointConfig`, passing the URL of the endpoint and the AWS Region as the parameters.

To learn how to set AWS STS regional endpoints using an environment variable for AWS SDKs, see [AWS STS Regionalized endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html) in the *AWS SDKs and Tools Reference Guide*.

For all other language and programming environment combinations, refer to the [documentation for the relevant SDK](https://aws.amazon.com/tools/).

## Managing global endpoint session tokens


Most AWS Regions are enabled for operations in all AWS services by default. Those Regions are automatically activated for use with AWS STS. Some Regions, such as Asia Pacific (Hong Kong), must be manually enabled. To learn more about enabling and disabling AWS Regions, see [Specify which AWS Regions your account can use](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) in the *AWS Account Management Reference Guide*. When you enable these AWS Regions, they are automatically activated for use with AWS STS. You cannot activate the AWS STS endpoint for a Region that is disabled. Session tokens that are valid in all AWS Regions include more characters than tokens that are valid in Regions that are enabled by default. Changing this setting might affect existing systems where you temporarily store tokens.

You can change this setting using the AWS Management Console, AWS CLI, or AWS API.

**To change the Region compatibility of session tokens for the global endpoint (console)**

1. Sign in as a root user or a user with permissions to perform IAM administration tasks. To change the compatibility of session tokens, you must have a policy that allows the `iam:SetSecurityTokenServicePreferences` action.

1. Open the [IAM console](https://console.aws.amazon.com/iam/home?#home). In the navigation pane, choose **Account settings**.

1. Under **Security Token Service (STS)** section **Session Tokens from the STS endpoints**. The **Global endpoint** indicates `Valid only in AWS Regions enabled by default`. Choose **Change**.

1. In the **Change region compatibility** dialog box, select **All AWS Regions**. Then choose **Save changes**.
**Note**  
Session tokens that are valid in all AWS Region include more characters than tokens that are valid in Regions that are enabled by default. Changing this setting might affect existing systems where you temporarily store tokens.

**To change the Region compatibility of session tokens for the global endpoint (AWS CLI)**  
Set the session token version. Version 1 tokens are valid only in AWS Regions that are available by default. These tokens do not work in manually enabled Regions, such as Asia Pacific (Hong Kong). Version 2 tokens are valid in all Regions. However, version 2 tokens include more characters and might affect systems where you temporarily store tokens.
+ [https://docs.aws.amazon.com/cli/latest/reference/iam/set-security-token-service-preferences.html](https://docs.aws.amazon.com/cli/latest/reference/iam/set-security-token-service-preferences.html)

**To change the Region compatibility of session tokens for the global endpoint (AWS API)**  
Set the session token version. Version 1 tokens are valid only in AWS Regions that are available by default. These tokens do not work in manually enabled Regions, such as Asia Pacific (Hong Kong). Version 2 tokens are valid in all Regions. However, version 2 tokens include more characters and might affect systems where you temporarily store tokens.
+ [https://docs.aws.amazon.com/IAM/latest/APIReference/API_SetSecurityTokenServicePreferences.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_SetSecurityTokenServicePreferences.html) 

# AWS STS Regions and endpoints


**Note**  
AWS has made changes to the AWS Security Token Service (AWS STS) global endpoint (`https://sts.amazonaws.com`) in Regions [enabled by default](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) to enhance its resiliency and performance. AWS STS requests to the global endpoint are automatically served in the same AWS Region as your workloads. These changes will not be deployed to opt-in Regions. We recommend that you use the appropriate AWS STS regional endpoints. For more information, see [AWS STS global endpoint changes](#reference_sts_global_endpoint_changes).

The following table lists the Regions and their endpoints. It indicates which ones are activated by default and which ones you can activate or deactivate.

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_region-endpoints.html)

¹You must [enable the Region](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html) to use it. This automatically activates AWS STS. You cannot manually activate or deactivate AWS STS in these Regions.

²To use AWS in China, you need an account and credentials specific to AWS in China.

## AWS STS global endpoint changes


AWS has made changes to the AWS Security Token Service (AWS STS) global endpoint (`https://sts.amazonaws.com`) in Regions [enabled by default](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) to enhance its resiliency and performance. Previously, all requests to the AWS STS global endpoint were served by a single AWS Region, US East (N. Virginia). Now in Regions [enabled by default](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html), requests to the AWS STS global endpoint are automatically served in the same Region where the request originates, rather than the US East (N. Virginia) Region. These changes will not be deployed to opt-in Regions.

With this change, AWS STS will process your request based on the originating Region and DNS resolver used. Requests to the AWS STS global endpoint are served in the same Region as your AWS deployed workload if the DNS request for the AWS STS global endpoint is handled by the Amazon DNS server in Regions that are enabled by default. Requests to the AWS STS global endpoint will continue to be served in US East (N. Virginia) Region if your request originated from opt-in Regions or if your request was resolved using a DNS resolver other than the Amazon DNS server. For more information about Amazon DNS, see [ Amazon DNS server](https://docs.aws.amazon.com/vpc/latest/userguide/AmazonDNS-concepts.html#AmazonDNS) in the *Amazon Virtual Private Cloud User Guide*.

The following table shows how requests to the AWS STS global endpoint are routed based on your DNS provider.


| DNS Resolver | Requests to the AWS STS global endpoint routed to the local AWS Region? | 
| --- | --- | 
|  Amazon DNS resolver in a Amazon VPC in an Region enabled by default  |  Yes  | 
|  Amazon DNS resolver in a Amazon VPC in an opt-in Region  |  No, the request will be routed to the US East (N. Virginia) Region  | 
|  DNS resolver provided by your ISP, a public DNS provider, or any other DNS provider  |  No, the request will be routed to the US East (N. Virginia) Region  | 

To ensure minimal disruption to your existing processes, AWS has implemented the following measures:
+ AWS CloudTrail logs for requests made to the AWS STS global endpoint are sent to the US East (N. Virginia) Region. CloudTrail logs for requests served by AWS STS Regional endpoints will continue to be logged to their respective Region in CloudTrail.
+ CloudTrail logs for operations performed by the AWS STS global endpoint and Regional endpoints have additional fields `endpointType` and `awsServingRegion` to indicate which endpoint and Region served the request. For CloudTrail log examples, see [Example AWS STS API event using the global endpoint in CloudTrail log file](cloudtrail-integration.md#stscloudtrailexample-assumerole-sts-global-endpoint).
+ Requests made to the AWS STS global endpoint have a value of `us-east-1` for the `aws:RequestedRegion` condition key, regardless of which Region served the request.
+ Requests handled by the AWS STS global endpoint do not share a requests per second quota with Regional AWS STS endpoints.

If you have workloads in an opt-in Region and are still using the AWS STS global endpoint, we recommend migrating to AWS STS regional endpoints for improved resiliency and performance. For more information about configuring regional AWS STS endpoints, see [AWS STS Regional endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html) in the *AWS SDKs and Tools Reference Guide*.

## AWS CloudTrail and Regional endpoints


Calls to regional and global endpoints are logged in the `tlsDetails` field in AWS CloudTrail. Calls to regional endpoints, such as `us-east-2.amazonaws.com`, are logged in CloudTrail to their appropriate region. Calls to the global endpoint, `sts.amazonaws.com`, are logged as calls to a global service. Events for global AWS STS endpoints are logged to us-east-1.

**Note**  
 `tlsDetails` can only be viewed for services that support this field. See [Services that support TLS details in CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-tls-details.html) in the *AWS CloudTrail User Guide*  
For more information, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md).

# Enable custom identity broker access to the AWS console
Enable custom identity broker console access

You can write and run code to create a URL that lets users who sign in to your organization's network securely access the AWS Management Console. The URL includes a sign-in token that you get from AWS and that authenticates the user to AWS. The resulting console session might include a distinct `AccessKeyId` due to federation. To trace the access key usage for federation sign-in through related CloudTrail events, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md) and [AWS Management Console sign-in events](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-aws-console-sign-in-events.html). 

**Note**  
If your organization uses an identity provider (IdP) that is compatible with SAML, you can set up access to the console without writing code. This works with providers like Microsoft's Active Directory Federation Services or open-source Shibboleth. For details, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md). 

To enable your organization's users to access the AWS Management Console, you can create a custom *identity broker* that performs the following steps:

1. Verify that the user is authenticated by your local identity system.

1. Call the AWS Security Token Service (AWS STS) [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) (recommended) or [GetFederationToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API operations to obtain temporary security credentials for the user. To learn about the different methods that you can use to assume a role, see [Methods to assume a role](id_roles_manage-assume.md). To learn how to pass optional session tags when you obtain your security credentials, see [Pass session tags in AWS STS](id_session-tags.md).
   + If you use one of the `AssumeRole*` API operations to get the temporary security credentials for a role, you can include the `DurationSeconds` parameter in your call. This parameter specifies the duration of your role session, from 900 seconds (15 minutes) up to the maximum session duration setting for the role. When you use `DurationSeconds` in an `AssumeRole*` operation, you must call it as an IAM user with long-term credentials. Otherwise, the call to the federation endpoint in step 3 fails. To learn how to view or change the maximum value for a role, see [Update the maximum session duration for a role](id_roles_update-role-settings.md#id_roles_update-session-duration).
   + If you use the `GetFederationToken` API operation to get the credentials, you can include the `DurationSeconds` parameter in your call. This parameter specifies the duration of your role session. The value can range from 900 seconds (15 minutes) to 129,600 seconds (36 hours). You can make this API call only by using the long-term AWS security credentials of an IAM user. You can also make these calls using AWS account root user credentials, but we do not recommend it. If you make this call as the root user, the default session lasts for one hour. Or you can specify a session from 900 seconds (15 minutes) up to 3,600 seconds (one hour). 

1. Call the AWS federation endpoint and supply the temporary security credentials to request a sign-in token.

1. Construct a URL for the console that includes the token:
   + If you use one of the `AssumeRole*` API operations in your URL, you can include the `SessionDuration` HTTP parameter. This parameter specifies the duration of the console session, from 900 seconds (15 minutes) to 43200 seconds (12 hours).
   + If you use the `GetFederationToken` API operation in your URL, you can include the `DurationSeconds` parameter. This parameter specifies the duration of the federated console session. The value can range from 900 seconds (15 minutes) to 129,600 seconds (36 hours). 
**Note**  
Your `SessionDuration` cannot be greater than or equal to the maximum session duration setting for the role you're assuming. For example, you're set the maximum session duration for the role you want to assume to 5 hours. Your `SessionDuration` parameter can be 16524 seconds or 4 hours and 59 seconds.
Do not use the `SessionDuration` HTTP parameter when you get temporary credentials with `GetFederationToken`. The operation will fail.
Using the credentials for one role to assume a different role is called [*role chaining*](id_roles.md#iam-term-role-chaining). When you use role chaining, your new credentials are limited to a maximum duration of one hour. When you use roles to [grant permissions to applications that run on EC2 instances](id_roles_use_switch-role-ec2.md), those applications are not subject to this limitation.
Do not use the `SessionDuration` HTTP parameter when you get temporary credentials through role chaining. The operation will fail.

1. Give the URL to the user or invoke the URL on the user's behalf.

The URL that the federation endpoint provides is valid for 15 minutes after it is created. This differs from the duration (in seconds) of the temporary security credential session that is associated with the URL. Those credentials are valid for the duration you specified when you created them, starting from the time they were created.

**Important**  
The URL grants access to your AWS resources through the AWS Management Console if you have enabled permissions in the associated temporary security credentials. For this reason, you should treat the URL as a secret. We recommend returning the URL through a secure redirect, for example, by using a 302 HTTP response status code over an SSL connection. For more information about the 302 HTTP response status code, go to [RFC 2616, section 10.3.3](https://datatracker.ietf.org/doc/html/rfc2616#section-10.3.3).

To complete these tasks, you can use the [HTTPS Query API for AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/APIReference/) and the [AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/). Or, you can use programming languages, such as Java, Ruby, or C\$1, along with the appropriate [AWS SDK](https://aws.amazon.com/tools/). Each of these methods is described in the following topics.

**Topics**
+ [

## Example code using IAM query API operations
](#STSConsoleLink_manual)
+ [

## Example code using Python
](#STSConsoleLink_programPython)
+ [

## Example code using Java
](#STSConsoleLink_programJava)
+ [

## Example showing how to construct the URL (Ruby)
](#STSConsoleLink_programRuby)

## Example code using IAM query API operations


You can construct a URL that gives roles and federated principals direct access to the AWS Management Console. This task uses the IAM and AWS STS HTTPS Query API. For more information about making query requests, see [Making Query Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html).

**Note**  
The following procedure contains examples of text strings. To enhance readability, line breaks have been added to some of the longer examples. When you create these strings for your own use, you should omit any line breaks.

**To give roles and federated principals access to your resources from the AWS Management Console**

1. Authenticate the user in your identity and authorization system.

1. Obtain temporary security credentials for the user. The temporary credentials consist of an access key ID, a secret access key, and a session token. For more information about creating temporary credentials, see [Temporary security credentials in IAM](id_credentials_temp.md).

   To get temporary credentials, you call either the AWS STS [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API (recommended) or the [GetFederationToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API. For more information about the differences between these API operations, see [Understanding the API Options for Securely Delegating Access to Your AWS Account](https://aws.amazon.com/blogs/security/understanding-the-api-options-for-securely-delegating-access-to-your-aws-account) in the AWS Security Blog.
**Important**  
When you use the [GetFederationToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API to create temporary security credentials, you must specify the permissions that the credentials grant to the user who assumes the role. For any of the API operations that begin with `AssumeRole*`, you use an IAM role to assign permissions. For the other API operations, the mechanism varies with the API. For more details, see [Permissions for temporary security credentials](id_credentials_temp_control-access.md). Additionally, if you use the `AssumeRole*` API operations, you must call them as an IAM user with long-term credentials. Otherwise, the call to the federation endpoint in step 3 fails.  


1. After you obtain the temporary security credentials, build them into a JSON session string to exchange them for a sign-in token. The following example shows how to encode the credentials. You replace the placeholder text with the appropriate values from the credentials that you receive in the previous step.

   ```
   {"sessionId":"*** temporary access key ID ***",
   "sessionKey":"*** temporary secret access key ***",
   "sessionToken":"*** session token ***"}
   ```

1. [URL encode](https://en.wikipedia.org/wiki/Percent-encoding) the session string from the previous step. Because the information that you are encoding is sensitive, we recommend that you avoid using a web service for this encoding. Instead, use a locally installed function or feature in your development toolkit to securely encode this information. You can use the `urllib.quote_plus` function in Python, the `URLEncoder.encode` function in Java, or the `CGI.escape` function in Ruby. See the examples later in this topic.

1. <a name="STSConsoleLink_manual_step5"></a>
**Note**  
AWS supports POST requests here.

   Send your request to the AWS federation endpoint:

   `https://region-code.signin.aws.amazon.com/federation` 

   For a list of possible *region-code* values, see the **Region** column in [AWS Sign-In endpoints](https://docs.aws.amazon.com/general/latest/gr/signin-service.html). You can optionally use the default AWS Sign-In federation endpoint:

   `https://signin.aws.amazon.com/federation` 

   The request must include the `Action` and `Session` parameters, and (optionally) if you used an [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation, a `SessionDuration` HTTP parameter as shown in the following example.

   ```
   Action = getSigninToken
   SessionDuration = time in seconds
   Session = *** the URL encoded JSON string created in steps 3 & 4 ***
   ```
**Note**  
The following instructions in this step only work using GET requests.

   The `SessionDuration` HTTP parameter specifies the duration of the console session. This is separate from the duration of the temporary credentials that you specify using the `DurationSeconds` parameter. You can specify a `SessionDuration` maximum value of 43,200 (12 hours). If the `SessionDuration` parameter is missing, then the session defaults to the duration of the credentials that you retrieved from AWS STS in step 2 (which defaults to one hour). See the [documentation for the `AssumeRole` API](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) for details about how to specify a duration using the `DurationSeconds` parameter. The ability to create a console session that is longer than one hour is intrinsic to the `getSigninToken` operation of the federation endpoint.
**Note**  
Your `SessionDuration` cannot be greater than or equal to the maximum session duration setting for the role you're assuming. For example, you're set the maximum session duration for the role you want to assume to 5 hours. Your `SessionDuration` parameter can be 16524 seconds or 4 hours and 59 seconds.
Do not use the `SessionDuration` HTTP parameter when you get temporary credentials with `GetFederationToken`. The operation will fail.
Using the credentials for one role to assume a different role is called [*role chaining*](id_roles.md#iam-term-role-chaining). When you use role chaining, your new credentials are limited to a maximum duration of one hour. When you use roles to [grant permissions to applications that run on EC2 instances](id_roles_use_switch-role-ec2.md), those applications are not subject to this limitation.
Do not use the `SessionDuration` HTTP parameter when you get temporary credentials through role chaining. The operation will fail.

   When you enable console sessions with an extended duration, you increase the risk of credential exposure. To help you mitigate this risk, you can immediately disable the active console sessions for any role by choosing **Revoke Sessions** on the **Role Summary** IAM console page. For more information, see [Revoke IAM role temporary security credentials](id_roles_use_revoke-sessions.md). 

    The following is an example of what your request might look like. The lines are wrapped here for readability, but you should submit it as a one-line string.

   ```
   https://signin.aws.amazon.com/federation
   ?Action=getSigninToken
   &SessionDuration=1800
   &Session=%7B%22sessionId%22%3A+%22ASIAJUMHIZPTOKTBMK5A%22%2C+%22sessionKey%22
   %3A+%22LSD7LWI%2FL%2FN%2BgYpan5QFz0XUpc8s7HYjRsgcsrsm%22%2C+%22sessionToken%2
   2%3A+%22FQoDYXdzEBQaDLbj3VWv2u50NN%2F3yyLSASwYtWhPnGPMNmzZFfZsL0Qd3vtYHw5A5dW
   AjOsrkdPkghomIe3mJip5%2F0djDBbo7SmO%2FENDEiCdpsQKodTpleKA8xQq0CwFg6a69xdEBQT8
   FipATnLbKoyS4b%2FebhnsTUjZZQWp0wXXqFF7gSm%2FMe2tXe0jzsdP0O12obez9lijPSdF1k2b5
   PfGhiuyAR9aD5%2BubM0pY86fKex1qsytjvyTbZ9nXe6DvxVDcnCOhOGETJ7XFkSFdH0v%2FYR25C
   UAhJ3nXIkIbG7Ucv9cOEpCf%2Fg23ijRgILIBQ%3D%3D%22%7D
   ```

   The response from the federation endpoint is a JSON document with a `SigninToken` value. It will look similar to the following example.

   ```
   {"SigninToken":"*** the SigninToken string ***"}
   ```

1. 
**Note**  
AWS supports POST requests here.

   Finally, create the URL that your users can use to access the AWS Management Console. The URL is the same federation URL endpoint that you used in [Step 5](#STSConsoleLink_manual_step5), plus the following parameters:

   ```
   ?Action = login
   &Issuer = *** the form-urlencoded URL for your internal sign-in page ***
   &Destination = *** the form-urlencoded URL to the desired AWS console page ***
   &SigninToken = *** the value of SigninToken received in the previous step ***
   ```
**Note**  
The following instructions in this step only work using GET API.

   The following example shows what the final URL might look like. The URL is valid for 15 minutes from the time it is created. The temporary security credentials and console session embedded within the URL are valid for the duration you specify in the `SessionDuration` HTTP parameter when you initially request them. 

   ```
   https://signin.aws.amazon.com/federation
   ?Action=login
   &Issuer=https%3A%2F%2Fexample.com
   &Destination=https%3A%2F%2Fconsole.aws.amazon.com%2F
   &SigninToken=VCQgs5qZZt3Q6fn8Tr5EXAMPLEmLnwB7JjUc-SHwnUUWabcRdnWsi4DBn-dvC
   CZ85wrD0nmldUcZEXAMPLE-vXYH4Q__mleuF_W2BE5HYexbe9y4Of-kje53SsjNNecATfjIzpW1
   WibbnH6YcYRiBoffZBGExbEXAMPLE5aiKX4THWjQKC6gg6alHu6JFrnOJoK3dtP6I9a6hi6yPgm
   iOkPZMmNGmhsvVxetKzr8mx3pxhHbMEXAMPLETv1pij0rok3IyCR2YVcIjqwfWv32HU2Xlj471u
   3fU6uOfUComeKiqTGX974xzJOZbdmX_t_lLrhEXAMPLEDDIisSnyHGw2xaZZqudm4mo2uTDk9Pv
   9l5K0ZCqIgEXAMPLEcA6tgLPykEWGUyH6BdSC6166n4M4JkXIQgac7_7821YqixsNxZ6rsrpzwf
   nQoS14O7R0eJCCJ684EXAMPLEZRdBNnuLbUYpz2Iw3vIN0tQgOujwnwydPscM9F7foaEK3jwMkg
   Apeb1-6L_OB12MZhuFxx55555EXAMPLEhyETEd4ZulKPdXHkgl6T9ZkIlHz2Uy1RUTUhhUxNtSQ
   nWc5xkbBoEcXqpoSIeK7yhje9Vzhd61AEXAMPLElbWeouACEMG6-Vd3dAgFYd6i5FYoyFrZLWvm
   0LSG7RyYKeYN5VIzUk3YWQpyjP0RiT5KUrsUi-NEXAMPLExMOMdoODBEgKQsk-iu2ozh6r8bxwC
   RNhujg
   ```

## Example code using Python


The following examples show how to use Python to programmatically construct a URL that gives users direct access to the AWS Management Console. There are two examples:
+ Federate via GET requests to AWS
+ Federate via POST requests to AWS

Both examples use the the [AWS SDK for Python (Boto3)](https://aws.amazon.com/tools/) and [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API to obtain temporary security credentials.

Do not include `SessionDuration` if your `AssumeRoleSession` credentials are from role chaining. If you include `SessionDuration`, the operation will fail.

### Use GET Requests


```
import urllib, json, sys
import requests # 'pip install requests'
import boto3 # AWS SDK for Python (Boto3) 'pip install boto3'

# Step 1: Authenticate user in your own identity system.

# Step 2: Using the access keys for an IAM user in your AWS account,
# call "AssumeRole" to get temporary access keys for the role or federated principal

# Note: Calls to AWS STS AssumeRole must be signed using the access key ID 
# and secret access key of an IAM user or using existing temporary credentials.
# The credentials can be in Amazon EC2 instance metadata, in environment variables, 
# or in a configuration file, and will be discovered automatically by the 
# client('sts') function. For more information, see the Python SDK docs:
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html#STS.Client.assume_role
sts_connection = boto3.client('sts')

assumed_role_object = sts_connection.assume_role(
    RoleArn="arn:aws:iam::account-id:role/ROLE-NAME",
    RoleSessionName="AssumeRoleSession",
)

# Step 3: Format resulting temporary credentials into JSON
url_credentials = {}
url_credentials['sessionId'] = assumed_role_object.get('Credentials').get('AccessKeyId')
url_credentials['sessionKey'] = assumed_role_object.get('Credentials').get('SecretAccessKey')
url_credentials['sessionToken'] = assumed_role_object.get('Credentials').get('SessionToken')
json_string_with_temp_credentials = json.dumps(url_credentials)

# Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with
# the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials 
# as parameters.
request_parameters = "?Action=getSigninToken"
request_parameters += "&SessionDuration=43200"
if sys.version_info[0] < 3:
    def quote_plus_function(s):
        return urllib.quote_plus(s)
else:
    def quote_plus_function(s):
        return urllib.parse.quote_plus(s)
request_parameters += "&Session=" + quote_plus_function(json_string_with_temp_credentials)
request_url = "https://signin.aws.amazon.com/federation" + request_parameters
r = requests.get(request_url)
# Returns a JSON document with a single element named SigninToken.
signin_token = json.loads(r.text)

# Step 5: Create URL where users can use the sign-in token to sign in to 
# the console. This URL must be used within 15 minutes after the
# sign-in token was issued.
request_parameters = "?Action=login" 
request_parameters += "&Issuer=Example.org" 
request_parameters += "&Destination=" + quote_plus_function("https://console.aws.amazon.com/")
request_parameters += "&SigninToken=" + signin_token["SigninToken"]
request_url = "https://signin.aws.amazon.com/federation" + request_parameters

# Send final URL to stdout
print (request_url)
```

### Use POST Requests


```
import urllib, json, sys
import requests # 'pip install requests'
import boto3 # AWS SDK for Python (Boto3) 'pip install boto3'
import os
from selenium import webdriver # 'pip install selenium', 'brew install chromedriver'

# Step 1: Authenticate user in your own identity system.

# Step 2: Using the access keys for an IAM user in your AAWS account,
# call "AssumeRole" to get temporary access keys for the role or federated principal

# Note: Calls to AWS STS AssumeRole must be signed using the access key ID 
# and secret access key of an IAM user or using existing temporary credentials.
# The credentials can be in Amazon EC2 instance metadata, in environment variables, 

# or in a configuration file, and will be discovered automatically by the 
# client('sts') function. For more information, see the Python SDK docs:
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html#STS.Client.assume_role
if sys.version_info[0] < 3:
    def quote_plus_function(s):
        return urllib.quote_plus(s)
else:
    def quote_plus_function(s):
        return urllib.parse.quote_plus(s)

sts_connection = boto3.client('sts')

assumed_role_object = sts_connection.assume_role(
    RoleArn="arn:aws:iam::account-id:role/ROLE-NAME",
    RoleSessionName="AssumeRoleDemoSession",
)

# Step 3: Format resulting temporary credentials into JSON
url_credentials = {}
url_credentials['sessionId'] = assumed_role_object.get('Credentials').get('AccessKeyId')
url_credentials['sessionKey'] = assumed_role_object.get('Credentials').get('SecretAccessKey')
url_credentials['sessionToken'] = assumed_role_object.get('Credentials').get('SessionToken')
json_string_with_temp_credentials = json.dumps(url_credentials)

# Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with
# the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials 
# as parameters.
request_parameters = {}
request_parameters['Action'] = 'getSigninToken'
request_parameters['SessionDuration'] = '43200'
request_parameters['Session'] = json_string_with_temp_credentials

request_url = "https://signin.aws.amazon.com/federation"
r = requests.post( request_url, data=request_parameters)

# Returns a JSON document with a single element named SigninToken.
signin_token = json.loads(r.text)

# Step 5: Create a POST request where users can use the sign-in token to sign in to 
# the console. The POST request must be made within 15 minutes after the
# sign-in token was issued.
request_parameters = {}
request_parameters['Action'] = 'login'
request_parameters['Issuer']='Example.org'
request_parameters['Destination'] = 'https://console.aws.amazon.com/'
request_parameters['SigninToken'] =signin_token['SigninToken']

jsrequest = '''
var form = document.createElement('form');
form.method = 'POST';
form.action = '{request_url}';
request_parameters = {request_parameters}
for (var param in request_parameters) {{
    if (request_parameters.hasOwnProperty(param)) {{
        const hiddenField = document.createElement('input');
        hiddenField.type = 'hidden';
        hiddenField.name = param;
        hiddenField.value = request_parameters[param];
        form.appendChild(hiddenField);
    }}
}}
document.body.appendChild(form);
form.submit();
'''.format(request_url=request_url, request_parameters=request_parameters)

driver = webdriver.Chrome()
driver.execute_script(jsrequest)
input("Press Enter to close the browser window...")
```

## Example code using Java


The following example shows how to use Java to programmatically construct a URL that gives users direct access to the AWS Management Console. The following code snippet uses the [AWS SDK for Java](http://aws.amazon.com/documentation/sdkforjava/).

```
import java.net.URLEncoder;
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// Available at http://www.json.org/java/index.html
import org.json.JSONObject;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;


/* Calls to AWS STS API operations must be signed using the access key ID 
   and secret access key of an IAM user or using existing temporary 
   credentials. The credentials should not be embedded in code. For 
   this example, the code looks for the credentials in a 
   standard configuration file.
*/
AWSCredentials credentials = 
  new PropertiesCredentials(
         AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties"));

AWSSecurityTokenServiceClient stsClient = 
  new AWSSecurityTokenServiceClient(credentials);

GetFederationTokenRequest getFederationTokenRequest = 
  new GetFederationTokenRequest();
getFederationTokenRequest.setDurationSeconds(1800);
getFederationTokenRequest.setName("UserName");

// A sample policy for accessing Amazon Simple Notification Service (Amazon SNS) in the console.

String policy = "{\"Version\":\"2012-10-17\",		 	 	 \"Statement\":[{\"Action\":\"sns:*\"," +
  "\"Effect\":\"Allow\",\"Resource\":\"*\"}]}";

getFederationTokenRequest.setPolicy(policy);

GetFederationTokenResult federationTokenResult = 
  stsClient.getFederationToken(getFederationTokenRequest);

Credentials federatedCredentials = federationTokenResult.getCredentials();

// The issuer parameter specifies your internal sign-in
// page, for example https://mysignin.internal.mycompany.com/.
// The console parameter specifies the URL to the destination console of the
// AWS Management Console. This example goes to Amazon SNS. 
// The signin parameter is the URL to send the request to.

String issuerURL = "https://mysignin.internal.mycompany.com/";
String consoleURL = "https://console.aws.amazon.com/sns";
String signInURL = "https://signin.aws.amazon.com/federation";
  
// Create the sign-in token using temporary credentials,
// including the access key ID,  secret access key, and session token.
String sessionJson = String.format(
  "{\"%1$s\":\"%2$s\",\"%3$s\":\"%4$s\",\"%5$s\":\"%6$s\"}",
  "sessionId", federatedCredentials.getAccessKeyId(),
  "sessionKey", federatedCredentials.getSecretAccessKey(),
  "sessionToken", federatedCredentials.getSessionToken());
              
// Construct the sign-in request with the request sign-in token action, a
// 12-hour console session duration, and the JSON document with temporary 
// credentials as parameters.

String getSigninTokenURL = signInURL + 
                           "?Action=getSigninToken" +
                           "&DurationSeconds=43200" + 
                           "&SessionType=json&Session=" + 
                           URLEncoder.encode(sessionJson,"UTF-8");

URL url = new URL(getSigninTokenURL);

// Send the request to the AWS federation endpoint to get the sign-in token
URLConnection conn = url.openConnection ();

BufferedReader bufferReader = new BufferedReader(new 
  InputStreamReader(conn.getInputStream()));  
String returnContent = bufferReader.readLine();

String signinToken = new JSONObject(returnContent).getString("SigninToken");

String signinTokenParameter = "&SigninToken=" + URLEncoder.encode(signinToken,"UTF-8");

// The issuer parameter is optional, but recommended. Use it to direct users
// to your sign-in page when their session expires.

String issuerParameter = "&Issuer=" + URLEncoder.encode(issuerURL, "UTF-8");

// Finally, present the completed URL for the AWS console session to the user

String destinationParameter = "&Destination=" + URLEncoder.encode(consoleURL,"UTF-8");
String loginURL = signInURL + "?Action=login" +
                     signinTokenParameter + issuerParameter + destinationParameter;
```

## Example showing how to construct the URL (Ruby)


The following example shows how to use Ruby to programmatically construct a URL that gives users direct access to the AWS Management Console. This code snippet uses the [AWS SDK for Ruby](http://aws.amazon.com/documentation/sdkforruby/). 

```
require 'rubygems'
require 'json'
require 'open-uri'
require 'cgi'
require 'aws-sdk'

# Create a new STS instance
# 
# Note: Calls to AWS STS API operations must be signed using an access key ID 
# and secret access key. The credentials can be in EC2 instance metadata 
# or in environment variables and will be automatically discovered by
# the default credentials provider in the AWS Ruby SDK. 
sts = Aws::STS::Client.new()

# The following call creates a temporary session that returns 
# temporary security credentials and a session token.
# The policy grants permissions to work
# in the AWS SNS console.

session = sts.get_federation_token({
  duration_seconds: 1800,
  name: "UserName",
  policy: "{\"Version\":\"2012-10-17\",		 	 	 \"Statement\":{\"Effect\":\"Allow\",\"Action\":\"sns:*\",\"Resource\":\"*\"}}",
})

# The issuer value is the URL where users are directed (such as
# to your internal sign-in page) when their session expires.
#
# The console value specifies the URL to the destination console.
# This example goes to the Amazon SNS console.
#
# The sign-in value is the URL of the AWS STS federation endpoint.
issuer_url = "https://mysignin.internal.mycompany.com/"
console_url = "https://console.aws.amazon.com/sns"
signin_url = "https://signin.aws.amazon.com/federation"

# Create a block of JSON that contains the temporary credentials
# (including the access key ID, secret access key, and session token).
session_json = {
  :sessionId => session.credentials[:access_key_id],
  :sessionKey => session.credentials[:secret_access_key],
  :sessionToken => session.credentials[:session_token]
}.to_json

# Call the federation endpoint, passing the parameters
# created earlier and the session information as a JSON block. 
# The request returns a sign-in token that's valid for 15 minutes.
# Signing in to the console with the token creates a session 
# that is valid for 12 hours.
get_signin_token_url = signin_url + 
                       "?Action=getSigninToken" + 
                       "&SessionType=json&Session=" + 
                       CGI.escape(session_json)

returned_content = URI.parse(get_signin_token_url).read

# Extract the sign-in token from the information returned
# by the federation endpoint.
signin_token = JSON.parse(returned_content)['SigninToken']
signin_token_param = "&SigninToken=" + CGI.escape(signin_token)

# Create the URL to give to the user, which includes the
# sign-in token and the URL of the console to open.
# The "issuer" parameter is optional but recommended.
issuer_param = "&Issuer=" + CGI.escape(issuer_url)
destination_param = "&Destination=" + CGI.escape(console_url)
login_url = signin_url + "?Action=login" + signin_token_param + 
  issuer_param + destination_param
```

# Tags for AWS Identity and Access Management resources
Tags for IAM resources

A *tag* is a custom attribute label that you can assign to an AWS resource. Each tag has two parts:
+ A *tag key* (for example, `CostCenter`, `Environment`, `Project`, or `Purpose`).
+ An optional field known as a *tag value* (for example, `111122223333`, `Production`, or a team name). Omitting the tag value is the same as using an empty string.

Together these are known as key-value pairs. For limits on the number of tags you can have on IAM resources, see [IAM and AWS STS quotas](reference_iam-quotas.md).

**Note**  
For details about case sensitivity for tag keys and tag key values, see [Case sensitivity](#case-sensitivity).

Tags help you identify and organize your AWS resources. Many AWS services support tagging, so you can assign the same tag to resources from different services to indicate that the resources are related. For example, you can assign the same tag to an IAM role that you assign to an Amazon S3 bucket. For more information about tagging strategies, see the *[Tagging AWS resources](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html) User Guide*.

In addition to identifying, organizing, and tracking your IAM resources with tags, you can use tags in IAM policies to help control who can view and interact with your resources. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

**Topics**
+ [

## Choose an AWS tag naming convention
](#id_tags_naming)
+ [

## Rules for tagging in IAM and AWS STS
](#id_tags_rules)
+ [

# Tag IAM users
](id_tags_users.md)
+ [

# Tag IAM roles
](id_tags_roles.md)
+ [

# Tag customer managed policies
](id_tags_customer-managed-policies.md)
+ [

# Tag OpenID Connect (OIDC) identity providers
](id_tags_oidc.md)
+ [

# Tag IAM SAML identity providers
](id_tags_saml.md)
+ [

# Tag instance profiles for Amazon EC2 roles
](id_tags_instance-profiles.md)
+ [

# Tag server certificates
](id_tags_server-certificates.md)
+ [

# Tag virtual MFA devices
](id_tags_virtual-mfa.md)
+ [

# Pass session tags in AWS STS
](id_session-tags.md)

## Choose an AWS tag naming convention


When you begin attaching tags to your IAM resources, choose your tag naming convention carefully. Apply the same convention to all of your AWS tags. This is especially important if you use tags in policies to control access to AWS resources. If you already use tags in AWS, review your naming convention and adjust it accordingly.

**Note**  
If your account is a member of AWS Organizations, see [Tag policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) in the AWS Organizations user guide to learn more about using tags in AWS Organizations.

### Best practices for tag naming


These are some best practices and naming conventions for tags.

Ensure that tag names are used consistently. For example, the tags `CostCenter` and `costcenter` are different, so one might be configured as a cost allocation tag for financial analysis and reporting and the other one might not be. Similarly, the `Name` tag appears in the AWS Console for many resources, but the `name` tag does not. For details about case sensitivity for tag keys and tag key values, see [Case sensitivity](#case-sensitivity).

A number of tags are predefined by AWS or created automatically by various AWS services. Many AWS-defined tags names use all lowercase, with hyphens separating words in the name, and prefixes to identify the source service for the tag. For example: 
+ `aws:ec2spot:fleet-request-id` identifies the Amazon EC2 Spot Instance Request that launched the instance.
+ `aws:cloudformation:stack-name` identifies the CloudFormation stack that created the resource. 
+ `elasticbeanstalk:environment-name` identifies the application that created the resource.

Consider naming your tags using all lowercase, with hyphens separating words, and a prefix identifying the organization name or abbreviated name. For example, for a fictitious company named *AnyCompany*, you might define tags such as:
+ `anycompany:cost-center` to identify the internal Cost Center code 
+ `anycompany:environment-type` to identify whether the environment is development, test, or production
+ `anycompany:application-id` to identify the application the resource was created for 

The prefix ensures that tags are clearly identified as having been defined by your organization and not by AWS or a third-party tool that you may be using. Using all lowercase with hyphens for separators avoids confusion about how to capitalize a tag name. For example, `anycompany:project-id` is simpler to remember than `ANYCOMPANY:ProjectID`, `anycompany:projectID`, or `Anycompany:ProjectId`.

## Rules for tagging in IAM and AWS STS


A number of conventions govern the creation and application of tags in IAM and AWS STS.

### Naming tags


Observe the following conventions when formulating a tag naming convention for IAM resources, AWS STS assume-role sessions, and AWS STS federated user sessions:

**Character requirements** – Tag keys and values can include any combination of letters, numbers, spaces, and \$1 . : / = \$1 - @ symbols.

**Case sensitivity** – Case sensitivity for tag keys differs depending on the type of IAM resource that is tagged. Tag key values for IAM users and roles are not case sensitive, but case is preserved. This means that you cannot have separate **Department** and **department** tag keys. If you have tagged a user with the **Department=finance** tag and you add the **department=hr** tag, it replaces the first tag. A second tag is not added.

For other IAM resource types, tag key values are case sensitive. That means you can have separate **Costcenter** and **costcenter** tag keys. For example, if you have tagged a customer managed policy with the **Costcenter = 1234** tag and you add the **costcenter = 5678** tag, the policy will have both the **Costcenter** and **costcenter** tag keys.

As a best practice, we recommend that you avoid using similar tags with inconsistent case treatment. We recommend that you decide on a strategy for capitalizing tags, and consistently implement that strategy across all resource types. To learn more about best practices for tagging, see [Tagging AWS Resources](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) in the AWS General Reference.

The following lists show the differences in case sensitivity for tag keys that are attached to IAM resources.

Tag key values are **not** case sensitive:
+ IAM roles
+ IAM users

Tag key values are case sensitive:
+ Customer managed policies
+ Instance profiles
+ OpenID Connect identity providers
+ SAML identity providers
+ Server certificates
+ Virtual MFA devices

Additionally, the following rules apply:
+ You cannot create a tag key or value that begins with the text **aws:**. This tag prefix is reserved for AWS internal use.
+ You can create a tag with an empty value such as **phoneNumber = **. You cannot create an empty tag key.
+ You cannot specify multiple values in a single tag, but you can create a custom multivalue structure in the single value. For example, assume that the user Zhang works on the engineering team and the QA team. If you attach the **team = Engineering** tag and then attach the **team = QA** tag, you change the value of the tag from **Engineering** to **QA**. Instead, you can include multiple values in a single tag with a custom separator. In this example, you could attach the **team = Engineering:QA** tag to Zhang.
**Note**  
To control access to engineers in this example using the **team** tag, you must create a policy that allows for every configuration that might include **Engineering**, including **Engineering:QA**. To learn more about using tags in policies, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

### Applying and editing tags


Observe the following conventions when attaching tags to IAM resources:
+ You can tag most IAM resources, but not groups, assumed roles, access reports, or hardware-based MFA devices.
+ You cannot use Tag Editor to tag IAM resources. Tag Editor does not support IAM tags. For information about using Tag Editor with other services, see [Working with Tag Editor](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/tag-editor.html) in the *AWS Resource Groups User Guide*.
+ To tag an IAM resource, you must have specific permissions. To tag or untag resources, you must also have permission to list tags. For more information, see the list of topics for each IAM resource at the end of this page. 
+ The number and size of IAM resources in an AWS account are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md).
+ You can apply the same tag to multiple IAM resources. For example, suppose you have a department named `AWS_Development` with 12 members. You can have 12 users and a role with the tag key of **department** and a value of **awsDevelopment** (**department = awsDevelopment**). You can also use the same tag on resources in other [services that support tagging](reference_aws-services-that-work-with-iam.md).
+ IAM entities (users or roles) cannot have multiple instances of the same tag key. For example, if you have a user with the tag key-value pair **costCenter = 1234**, you can then attach the tag key-value pair **costCenter = 5678**. IAM updates the value of the **costCenter** tag to **5678**.
+ To edit a tag that is attached to an IAM entity (user or role), attach a tag with a new value to overwrite the existing tag. For example, assume that you have a user with the tag key-value pair **department = Engineering**. If you need to move the user to the QA department, then you can attach the **department = QA** tag key-value pair to the user. This results in the **Engineering** value of the **department** tag key being replaced with the **QA** value.

# Tag IAM users


You can use IAM tag key-value pairs to add custom attributes to an IAM user. For example, to add location information to a user, you can add the tag key **location** and the tag value **us\$1wa\$1seattle**. Or you could use three separate location tag key-value pairs: **loc-country = us**, **loc-state = wa**, and **loc-city = seattle**. You can use tags to control a user's access to resources or to control what tags can be attached to a user. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging IAM users


You must configure permissions to allow an IAM user to tag other users. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListUserTags`
+ `iam:TagUser`
+ `iam:UntagUser`

**To allow an IAM user to add, list, or remove a tag for a specific user**  
Add the following statement to the permissions policy for the IAM user that needs to manage tags. Use your account number and replace *<username>* with the name of the user whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListUserTags",
        "iam:TagUser",
        "iam:UntagUser"
    ],
    "Resource": "arn:aws:iam::<account-number>:user/<username>"
}
```

**To allow an IAM user to self-manage tags**  
Add the following statement to the permissions policy for users to allow users to manage their own tags. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListUserTags",
        "iam:TagUser",
        "iam:UntagUser"
    ],
    "Resource": "arn:aws:iam::user/${aws:username}"
}
```

**To allow an IAM user to add a tag to a specific user**  
Add the following statement to the permissions policy for the IAM user that needs to add, but not remove, tags for a specific user.

**Note**  
The `iam:TagUser` action requires that you also include the `iam:ListUserTags` action.

To use this policy, replace *<username>* with the name of the user whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListUserTags",
        "iam:TagUser"
    ],
    "Resource": "arn:aws:iam::<account-number>:user/<username>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on IAM users (console)


You can manage tags for IAM users from the AWS Management Console.

**To manage tags on users (console)**

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 console, choose **Users** and then choose the name of the user that you want to edit.

1. Choose the **Tags** tab and then complete one of the following actions:
   + Choose **Add new tag** if the user does not yet have tags.
   + Choose **Manage tags** to manage the existing set of tags.

1. Add or remove tags to complete the set of tags. Then choose **Save changes**.

## Managing tags on IAM users (AWS CLI or AWS API)


You can list, attach, or remove tags for IAM users. You can use the AWS CLI or the AWS API to manage tags for IAM users.

**To list the tags currently attached to an IAM user (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-user-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-user-tags.html)
+ AWS API: [ListUserTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserTags.html)

**To attach tags to an IAM user (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-user](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-user.html)
+ AWS API: [TagUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagUser.html)

**To remove tags from an IAM user (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-user](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-user.html)
+ AWS API: [UntagUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagUser.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag IAM roles


You can use IAM tag key-value pairs to add custom attributes to an IAM role. For example, to add location information to a role, you can add the tag key **location** and the tag value **us\$1wa\$1seattle**. Or you could use three separate location tag key-value pairs: **loc-country = us**, **loc-state = wa**, and **loc-city = seattle**. You can use tags to control a role's access to resources or to control what tags can be attached to a role. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging IAM roles


You must configure permissions to allow an IAM role to tag other entities (users or roles). You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListRoleTags`
+ `iam:TagRole`
+ `iam:UntagRole`
+ `iam:ListUserTags`
+ `iam:TagUser`
+ `iam:UntagUser`

**To allow an IAM role to add, list, or remove a tag for a specific user**  
Add the following statement to the permissions policy for the IAM role that needs to manage tags. Use your account number and replace *<username>* with the name of the user whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListUserTags",
        "iam:TagUser",
        "iam:UntagUser"
    ],
    "Resource": "arn:aws:iam::<account-number>:user/<username>"
}
```

**To allow an IAM role to add a tag to a specific user**  
Add the following statement to the permissions policy for the IAM role that needs to add, but not remove, tags for a specific user.

To use this policy, replace *<username>* with the name of the user whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListUserTags",
        "iam:TagUser"
    ],
    "Resource": "arn:aws:iam::<account-number>:user/<username>"
}
```

**To allow an IAM role to add, list, or remove a tag for a specific role**  
Add the following statement to the permissions policy for the IAM role that needs to manage tags. Replace *<rolename>* with the name of the role whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListRoleTags",
        "iam:TagRole",
        "iam:UntagRole"
    ],
    "Resource": "arn:aws:iam::<account-number>:role/<rolename>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on IAM roles (console)


You can manage tags for IAM roles from the AWS Management Console.

**To manage tags on roles (console)**

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 console, choose **Roles** and then choose the name of the role that you want to edit.

1. Choose the **Tags** tab and then complete one of the following actions:
   + Choose **Add new tag** if the role does not yet have tags.
   + Choose **Manage tags** to manage the existing set of tags.

1. Add or remove tags to complete the set of tags. Then, choose **Save changes**.

## Managing tags on IAM roles (AWS CLI or AWS API)


You can list, attach, or remove tags for IAM roles. You can use the AWS CLI or the AWS API to manage tags for IAM roles.

**To list the tags currently attached to an IAM role (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-role-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-role-tags.html)
+ AWS API: [ListRoleTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRoleTags.html)

**To attach tags to an IAM role (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)
+ AWS API: [TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

**To remove tags from an IAM role (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-role.html)
+ AWS API: [UntagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagRole.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag customer managed policies


You can use IAM tag key-value pairs to add custom attributes to your customer managed policies. For example, to tag a policy with department information, you can add the tag key **Department** and the tag value **eng**. Or, you might want to tag policies to indicate that they are for a specific environment, such as **Environment = lab**. You can use tags to control access to resources or to control what tags can be attached to a resource. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging customer managed policies


You must configure permissions to allow an IAM entity (users or roles) to tag customer managed policies. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListPolicyTags`
+ `iam:TagPolicy`
+ `iam:UntagPolicy`

**To allow an IAM entity (user or role) to add, list, or remove a tag for a customer managed policy**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<policyname>* with the name of the policy whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListPolicyTags",
        "iam:TagPolicy",
        "iam:UntagPolicy"
    ],
    "Resource": "arn:aws:iam::<account-number>:policy/<policyname>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific customer managed policy**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific policy. 

**Note**  
The `iam:TagPolicy` action requires that you also include the `iam:ListPolicyTags` action.

To use this policy, replace *<policyname>* with the name of the policy whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListPolicyTags",
        "iam:TagPolicy"
    ],
    "Resource": "arn:aws:iam::<account-number>:policy/<policyname>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on IAM customer managed policies (console)


You can manage tags for IAM customer managed policies from the AWS Management Console.

**To manage tags on customer managed policies (console)**

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 console, choose **Policies** and then choose the name of the customer managed policy that you want to edit.

1. Choose the **Tags** tab and then choose **Manage tags**.

1. Add or remove tags to complete the set of tags. Then choose **Save changes**.

## Managing tags on IAM customer managed policies (AWS CLI or AWS API)


You can list, attach, or remove tags for IAM customer managed policies. You can use the AWS CLI or the AWS API to manage tags for IAM customer managed policies.

**To list the tags currently attached to an IAM customer managed policy (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-policy-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-policy-tags.html)
+ AWS API: [ListPolicyTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicyTags.html)

**To attach tags to an IAM customer managed policy(AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-policy.html)
+ AWS API: [TagPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagPolicy.html)

**To remove tags from an IAM customer managed policy (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-policy.html)
+ AWS API: [UntagPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagPolicy.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag OpenID Connect (OIDC) identity providers
Tag OIDC identity providers

You can use IAM tag key-values to add custom attributes to IAM OpenID Connect (OIDC) identity providers. For example, to identify an OIDC identity provider, you can add the tag key **google** and the tag value **oidc**. You can use tags to control access to resources or to control what tags can be attached to an object. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

## Permissions required for tagging IAM OIDC identity providers


You must configure permissions to allow an IAM entity (user or role) to tag IAM OIDC identity providers. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListOpenIDConnectProviderTags`
+ `iam:TagOpenIDConnectProvider`
+ `iam:UntagOpenIDConnectProvider`

**To allow an IAM entity to add, list, or remove a tag for an IAM OIDC identity provider**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<OIDCProviderName>* with the name of the OIDC provider whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListOpenIDConnectProviderTags",
        "iam:TagOpenIDConnectProvider",
        "iam:UntagOpenIDConnectProvider"
    ],
    "Resource": "arn:aws:iam::<account-number>:oidc-provider/<OIDCProviderName>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific IAM OIDC identity provider**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific identity provider.

**Note**  
The `iam:TagOpenIDConnectProvider` action requires that you also include the `iam:ListOpenIDConnectProviderTags` action.

To use this policy, replace *<OIDCProviderName>* with the name of the OIDC provider whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListOpenIDConnectProviderTags",
        "iam:TagOpenIDConnectProvider"
    ],
    "Resource": "arn:aws:iam::<account-number>:oidc-provider/<OIDCProviderName>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on IAM OIDC identity providers (console)


You can manage tags for IAM OIDC identity providers from the AWS Management Console.

**To manage tags on OIDC identity providers (console)**

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 console, choose **Identity providers** and then choose the name of the identity provider that you want to edit.

1. Choose the **Tags** tab, then in the **Tags** section, choose **Manage tags** and then complete one of the following actions:
   + Choose **Add tag** if the OIDC identity provider does not yet have tags or to add a new tag.
   + Edit existing tag keys and values.
   + Choose **Remove tag** to remove a tag.

1. Then choose **Save changes**.

## Managing tags on IAM OIDC identity providers (AWS CLI or AWS API)


You can list, attach, or remove tags for IAM OIDC identity providers. You can use the AWS CLI or the AWS API to manage tags for IAM OIDC identity providers.

**To list the tags currently attached to an IAM OIDC identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-open-id-connect-provider-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-provider-tags.html)
+ AWS API: [ListOpenIDConnectProviderTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviderTags.html)

**To attach tags to an IAM OIDC identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-open-id-connect-provider](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-open-id-connect-provider.html)
+ AWS API: [TagOpenIDConnectProvider](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagOpenIDConnectProvider.html)

**To remove tags from an IAM OIDC identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-open-id-connect-provider](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-open-id-connect-provider.html)
+ AWS API: [UntagOpenIDConnectProvider](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagOpenIDConnectProvider.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag IAM SAML identity providers


You can use IAM tag key-value pairs to add custom attributes to SAML identity providers. For example, to identify a provider, you can add the tag key **okta** and the tag value **saml**. You can use tags to control access to resources or to control what tags can be attached to an object. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

## Permissions required for tagging SAML identity providers


You must configure permissions to allow an IAM entity (users or roles) to tag SAML 2.0–based Identity Providers (IdPs). You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListSAMLProviderTags`
+ `iam:TagSAMLProvider`
+ `iam:UntagSAMLProvider`

**To allow an IAM entity (user or role) to add, list, or remove a tag for a SAML identity provider**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<SAMLProviderName>* with the name of the SAML provider whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListSAMLProviderTags",
        "iam:TagSAMLProvider",
        "iam:UntagSAMLProvider"
    ],
    "Resource": "arn:aws:iam::<account-number>:saml-provider/<SAMLProviderName>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific SAML identity provider**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific SAML provider.

**Note**  
The `iam:TagSAMLProvider` action requires that you also include the `iam:ListSAMLProviderTags` action.

To use this policy, replace *<SAMLProviderName>* with the name of the SAML provider whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListSAMLProviderTags",
        "iam:TagSAMLProvider"
    ],
    "Resource": "arn:aws:iam::<account-number>:saml-provider/<SAMLProviderName>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on IAM SAML identity providers (console)


You can manage tags for IAM SAML Identity Providers from the AWS Management Console.

**To manage tags on SAML identity providers (console)**

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 console, choose **Identity providers** and then choose the name of the SAML identity provider that you want to edit.

1. Choose the **Tags** tab, then in the **Tags** section, choose **Manage tags** and then complete one of the following actions:
   + Choose **Add tag** if the SAML identity provider does not yet have tags or to add a new tag.
   + Edit existing tag keys and values.
   + Choose **Remove tag** to remove a tag.

1. Add or remove tags to complete the set of tags. Then choose **Save changes**.

## Managing tags on IAM SAML identity providers (AWS CLI or AWS API)


You can list, attach, or remove tags for IAM SAML identity providers. You can use the AWS CLI or the AWS API to manage tags for IAM SAML identity providers.

**To list the tags currently attached to an SAML identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-saml-provider-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-provider-tags.html)
+ AWS API: [ListSAMLProviderTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviderTags.html)

**To attach tags to a SAML identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-saml-provider](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-saml-provider.html)
+ AWS API: [TagSAMLProvider](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagSAMLProvider.html)

**To remove tags from a SAML identity provider (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-saml-provider](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-saml-provider.html)
+ AWS API: [UntagSAMLProvider](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagSAMLProvider.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag instance profiles for Amazon EC2 roles
Tagging instance profiles

When you launch an Amazon EC2 instance, you specify an IAM role to associate with the instance. An instance profile is a container for an IAM role that you can use to pass role information to an Amazon EC2 instance when the instance starts. You can tag instance profiles when you use the AWS CLI or AWS API.

You can use IAM tag key-value pairs to add custom attributes to an instance profile. For example, to add department information to an instance profile, you can add the tag key **access-team** and the tag value **eng**. Doing this gives principals with matching tags access to instance profiles with the same tag. You could use multiple tag key-value pairs to specify a team and project: **access-team = eng **, and **project = peg**. You can use tags to control a user's access to resources or to control what tags can be attached to a user. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging instance profiles


You must configure permissions to allow an IAM entity (user or role) to tag instance profiles. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListInstanceProfileTags`
+ `iam:TagInstanceProfile`
+ `iam:UntagInstanceProfile`

**To allow an IAM entity (user or role) to add, list, or remove a tag for an instance profile**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<InstanceProfileName>* with the name of the instance profile whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListInstanceProfileTags",
        "iam:TagInstanceProfile",
        "iam:UntagInstanceProfile"
    ],
    "Resource": "arn:aws:iam::<account-number>:instance-profile/<InstanceProfileName>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific instance profile**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific instance profile. 

**Note**  
The `iam:TagInstanceProfile` action requires that you also include the `iam:ListInstanceProfileTags` action.

To use this policy, replace *<InstanceProfileName>* with the name of the instance profile whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListInstanceProfileTags",
        "iam:TagInstanceProfile"
    ],
    "Resource": "arn:aws:iam::<account-number>:instance-profile/<InstanceProfileName>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on instance profiles (AWS CLI or AWS API)


You can list, attach, or remove tags for instance profiles. You can use the AWS CLI or the AWS API to manage tags for instance profiles.

**To list the tags currently attached to an instance profile (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-instance-profile-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profile-tags.html)
+ AWS API: [ListInstanceProfileTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfileTags.html)

**To attach tags to an instance profile (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-instance-profile.html)
+ AWS API: [TagInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html)

**To remove tags from an instance profile (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-instance-profile.html)
+ AWS API: [UntagInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagInstanceProfile.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag server certificates


If you use IAM to manage SSL/TLS certificates, you can tag server certificates in IAM using the AWS CLI or AWS API. For certificates in a Region supported by AWS Certificate Manager (ACM), we recommend that you use ACM instead of IAM to provision, manage, and deploy your server certificates. In unsupported Regions, you must use IAM as a certificate manager. To learn which Regions ACM supports, see [AWS Certificate Manager endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/acm.html) in the *AWS General Reference*.

You can use IAM tag key-value pairs to add custom attributes to a server certificate. For example, to add information about the owner or administrator of a server certificate, add the tag key **owner** and the tag value **net-eng**. Or you can specify a cost center by adding the tag key **CostCenter** and the tag value **1234**. You can use tags to control access to resources or to control what tags can be attached to resources. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging server certificates


You must configure permissions to allow an IAM entity (user or role) to tag server certificates. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListServerCertificateTags`
+ `iam:TagServerCertificate`
+ `iam:UntagServerCertificate`

**To allow an IAM entity (user or role) to add, list, or remove a tag for a server certificate**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<CertificateName>* with the name of the server certificate whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListServerCertificateTags",
        "iam:TagServerCertificate",
        "iam:UntagServerCertificate"
    ],
    "Resource": "arn:aws:iam::<account-number>:server-certificate/<CertificateName>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific server certificate**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific server certificate.

**Note**  
The `iam:TagServerCertificate` action requires that you also include the `iam:ListServerCertificateTags` action.

To use this policy, replace *<CertificateName>* with the name of the server certificate whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListServerCertificateTags",
        "iam:TagServerCertificate"
    ],
    "Resource": "arn:aws:iam::<account-number>:server-certificate/<CertificateName>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on server certificates (AWS CLI or AWS API)


You can list, attach, or remove tags for server certificates. You can use the AWS CLI or the AWS API to manage tags for server certificates.

**To list the tags currently attached to a server certificate (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-server-certificate-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-server-certificate-tags.html)
+ AWS API: [ListServerCertificateTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServerCertificateTags.html)

**To attach tags to a server certificate(AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-server-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-server-certificate.html)
+ AWS API: [TagServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagServerCertificate.html)

**To remove tags from a server certificate (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-server-certificate](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-server-certificate.html)
+ AWS API: [UntagServerCertificate](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagServerCertificate.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Tag virtual MFA devices


You can use IAM tag key-value pairs to add custom attributes to a virtual MFA device. For example, to add cost center information for a user's virtual MFA device, you can add the tag key **CostCenter** and the tag value **1234**. You can use tags to control access to resources or to control what tags can be attached to an object. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md).

You can also use tags in AWS STS to add custom attributes when you assume a role or federate a user. For more information, see [Pass session tags in AWS STS](id_session-tags.md).

## Permissions required for tagging virtual MFA devices


You must configure permissions to allow an IAM entity (user or role) to tag virtual MFA devices. You can specify one or all of the following IAM tag actions in an IAM policy:
+ `iam:ListMFADeviceTags`
+ `iam:TagMFADevice`
+ `iam:UntagMFADevice`

**To allow an IAM entity (user or role) to add, list, or remove a tag for a virtual MFA device**  
Add the following statement to the permissions policy for the IAM entity that needs to manage tags. Use your account number and replace *<MFATokenID>* with the name of the virtual MFA device whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListMFADeviceTags",
        "iam:TagMFADevice",
        "iam:UntagMFADevice"
    ],
    "Resource": "arn:aws:iam::<account-number>:mfa/<MFATokenID>"
}
```

**To allow an IAM entity (user or role) to add a tag to a specific virtual MFA device**  
Add the following statement to the permissions policy for the IAM entity that needs to add, but not remove, tags for a specific MFA device.

**Note**  
The `iam:TagMFADevice` action requires that you also include the `iam:ListMFADeviceTags` action.

To use this policy, replace *<MFATokenID>* with the name of the virtual MFA device whose tags need to be managed. To learn how to create a policy using this example JSON policy document, see [Creating policies using the JSON editor](access_policies_create-console.md#access_policies_create-json-editor).

```
{
    "Effect": "Allow",
    "Action": [
        "iam:ListMFADeviceTags",
        "iam:TagMFADevice"
    ],
    "Resource": "arn:aws:iam::<account-number>:mfa/<MFATokenID>"
}
```

Alternatively, you can use an AWS managed policy such as [IAMFullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/IAMFullAccess) to provide full access to IAM.

## Managing tags on virtual MFA devices (AWS CLI or AWS API)


You can list, attach, or remove tags for a virtual MFA device. You can use the AWS CLI or the AWS API to manage tags for a virtual MFA device.

**To list the tags currently attached to a virtual MFA device (AWS CLI or AWS API)**
+ AWS CLI: [aws iam list-mfa-device-tags](https://docs.aws.amazon.com/cli/latest/reference/iam/list-mfa-device-tags.html)
+ AWS API: [ListMFADeviceTags](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADeviceTags.html)

**To attach tags to a virtual MFA device (AWS CLI or AWS API)**
+ AWS CLI: [aws iam tag-mfa-device](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-mfa-device.html)
+ AWS API: [TagMFADevice](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagMFADevice.html)

**To remove tags from a virtual MFA device (AWS CLI or AWS API)**
+ AWS CLI: [aws iam untag-mfa-device](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-mfa-device.html)
+ AWS API: [UntagMFADevice](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagMFADevice.html)

For information about attaching tags to resources for other AWS services, see the documentation for those services. 

For information about using tags to set more granular permissions with IAM permissions policies, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# Pass session tags in AWS STS
Pass session tags

Session tags are key-value pair attributes that you pass when you assume an IAM role or federate a user in AWS STS. You do this by making an AWS CLI or AWS API request through AWS STS or through your identity provider (IdP). When you use AWS STS to request temporary security credentials, you generate a session. Sessions expire and have [credentials](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html), such as an access key pair and a session token. When you use the session credentials to make a subsequent request, the [request context](reference_policies_elements_condition.md#AccessPolicyLanguage_RequestContext) includes the `aws:PrincipalTag` context key. You can use the `aws:PrincipalTag` key in the `Condition` element of your policies to allow or deny access based on those tags.

When you use temporary credentials to make a request, your principal might include a set of tags. These tags come from the following sources:

1. **Session tags** – The tags passed when you assume the role or federate the user using the AWS CLI or AWS API. For more information about these operations, see [Session tagging operations](#id_session-tags_operations).

1. **Incoming transitive session tags** – The tags inherited from a previous session in a role chain. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining) later in this topic.

1. **IAM tags** – The tags attached to your IAM assumed role.

**Topics**
+ [

## Session tagging operations
](#id_session-tags_operations)
+ [

## Things to know about session tags
](#id_session-tags_know)
+ [

## Permissions required to add session tags
](#id_session-tags_permissions-required)
+ [

## Passing session tags using AssumeRole
](#id_session-tags_adding-assume-role)
+ [

## Passing session tags using AssumeRoleWithSAML
](#id_session-tags_adding-assume-role-saml)
+ [

## Passing session tags using AssumeRoleWithWebIdentity
](#id_session-tags_adding-assume-role-idp)
+ [

## Passing session tags using GetFederationToken
](#id_session-tags_adding-getfederationtoken)
+ [

## Chaining roles with session tags
](#id_session-tags_role-chaining)
+ [

## Using session tags for ABAC
](#id_session-tags_using-abac)
+ [

## Viewing session tags in CloudTrail
](#id_session-tags_ctlogs)

## Session tagging operations


You can pass session tags using the following AWS CLI or AWS API operations in AWS STS. *The AWS Management Console **[Switch Role](id_roles_use_switch-role-console.md)** feature does not allow you to pass session tags.*

You can also set the session tags as transitive. Transitive tags persist during role chaining. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).

The following table compares methods for passing session tags.


|  Operation |  **Who can assume the role**  | **Method to pass tags** |  **Method to set transitive tags**  | 
| --- | --- | --- | --- | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API operation | IAM user or a session | Tags API parameter or --tags CLI option | TransitiveTagKeys API parameter or --transitive-tag-keys CLI option | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API operation | Any user authenticated using a SAML identity provider | PrincipalTag SAML attribute | TransitiveTagKeys SAML Attribute | 
| [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) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation | Any user authenticated using an OIDC provider | PrincipalTag OIDC token | TransitiveTagKeys OIDC token | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html) CLI or [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html) API operation | IAM user or root user | Tags API parameter or --tags CLI option | Not supported | 

Operations that support session tagging can fail under the following conditions:
+ You pass more than 50 session tags.
+ The plaintext of your session tag keys exceeds 128 characters.
+ The plaintext of your session tag values exceeds 256 characters.
+ The total size of the plaintext of session policies exceeds 2048 characters.
+ The total packed size of the combined session policies and tags is too large. If the operation fails, the error message shows how close the policies and tags combined come to the upper size limit, by percentage.

## Things to know about session tags
Things to know

Before you use session tags, review the following details about sessions and tags.
+ When using session tags, trust policies for all roles connected to the identity provider (IdP) passing tags must have the [`sts:TagSession`](#id_session-tags_permissions-required) permission. For roles without this permission in the trust policy, the `AssumeRole` operation fails.
+ When you request a session, you can specify principal tags as the session tags. The tags apply to requests that you make using the session's credentials.
+ Session tags use key-value pairs. For example, to add contact information to a session, you can add the session tag key `email` and the tag value `johndoe@example.com`.
+ Session tags must follow the [rules for naming tags in IAM and AWS STS](id_tags.md#id_tags_rules_creating). This topic includes information about case sensitivity and restricted prefixes that apply to your session tags.
+ New session tags override existing assumed role or federated user session tags with the same tag key, regardless of character case.
+ You cannot pass session tags using the AWS Management Console.
+ Session tags are valid only for the current session. 
+ Session tags support [role chaining](id_roles.md#iam-term-role-chaining). By default, AWS STS does not pass tags to subsequent role sessions. However, you can set session tags as transitive. Transitive tags persist during role chaining and replace matching `ResourceTag` values after the evaluation of the role trust policy. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).
+ You can use session tags to control access to resources or to control what tags can be passed into a subsequent session. For more information, see [IAM tutorial: Use SAML session tags for ABAC](tutorial_abac-saml.md).
+ You can view the principal tags for your session, including the session tags, in the AWS CloudTrail logs. For more information, see [Viewing session tags in CloudTrail](#id_session-tags_ctlogs).
+ You must pass a single value for each session tag. AWS STS does not support multi-valued session tags. 
+ You can pass a maximum of 50 session tags. The number and size of IAM resources in an AWS account are limited. For more information, see [IAM and AWS STS quotas](reference_iam-quotas.md).
+ An AWS conversion compresses the passed session policies and session tags combined into a packed binary format with a separate limit. If you exceed this limit, the AWS CLI or AWS API error message shows how close the policies and tags combined come to the upper size limit, by percentage.

## Permissions required to add session tags


In addition to the action that matches the API operation, you must have the following permissions-only action in your policy:

```
sts:TagSession
```

**Important**  
When using session tags, the role trust policies for all roles connected to an identity provider (IdP) must have the `sts:TagSession` permission. The `AssumeRole` operation fails for any role connected to an IdP passing session tags without this permission. If you don't want to update the role trust policy for each role, you can use a separate IdP instance for passing session tags. Then, add the `sts:TagSession` permission to only the roles connected to the separate IdP.

You can use the `sts:TagSession` action with the following condition keys.
+ `aws:PrincipalTag` – Compares the tag attached to the principal making the request with the tag you specified in the policy. For example, you can allow a principal to pass session tags only if the principal making the request has the specified tags.
+ `aws:RequestTag` – Compares the tag key-value pair passed in the request with the tag pair you specified in the policy. For example, you can allow the principal to pass the specified session tags, but only with the specified values.
+ `aws:ResourceTag` – Compares the tag key-value pair you specified in the policy with the key-value pair attached to the resource. For example, you can allow the principal to pass session tags only if the role they assume includes the specified tags.
+ `aws:TagKeys` – Compares the tag keys in a request with the keys you specified in the policy. For example, you can allow the principal to pass only session tags with the specified tag keys. This condition key limits the maximum set of session tags that can be passed.
+ `sts:TransitiveTagKeys` - Compares the transitive session tag keys in the request with those specified in the policy. For example, you can write a policy to allow a principal to set only specific tags as transitive. Transitive tags persist during role chaining. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).

For example, the following [role trust policy](id_roles.md#term_trust-policy) allows the `test-session-tags` user to assume the role with the attached policy. When that user assumes the role, they must use the AWS CLI or AWS API to pass the three required session tags and the required [external ID](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id). Additionally, the user can choose to set the `Project` and `Department` tags as transitive.

**Example role trust policy for session tags**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowIamUserAssumeRole",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"AWS": "arn:aws:iam::123456789012:user/test-session-tags"},
            "Condition": {
              "StringLike": {
                    "aws:RequestTag/Project": "*",
                    "aws:RequestTag/CostCenter": "*",
                    "aws:RequestTag/Department": "*"
                },
                "StringEquals": {"sts:ExternalId": "Example987"}
            }
        },
        {
            "Sid": "AllowPassSessionTagsAndTransitive",
            "Effect": "Allow",
            "Action": "sts:TagSession",
            "Principal": {"AWS": "arn:aws:iam::123456789012:user/test-session-tags"},
            "Condition": {
                "StringLike": {
                    "aws:RequestTag/Project": "*",
                    "aws:RequestTag/CostCenter": "*"
                },
                "StringEquals": {
                    "aws:RequestTag/Department": [
                        "Engineering",
                        "Marketing"
                    ]
                },
                "ForAllValues:StringEquals": {
                    "sts:TransitiveTagKeys": [
                        "Project",
                        "Department"
                    ]
                }
            }
        }
    ]
}
```

**What does this policy do?**
+ The `AllowIamUserAssumeRole` statement allows the `test-session-tags` user to assume the role with the attached policy. When that user assumes the role, they must pass the required session tags and [external ID](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id).
  + The first condition block of this statement requires the user to pass the `Project`, `CostCenter`, and `Department` session tags. The tag values do not matter in this statement, so you can use wildcards (\$1) for the tag values. This block ensures that user passes at least these three session tags. Otherwise, the operation fails. The user can pass additional tags.
  + The second condition block requires the user to pass an [external ID](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) with the value `Example987`.
+ The `AllowPassSessionTagsAndTransitive` statement allows the `sts:TagSession` permissions-only action. This action must be allowed before the user can pass session tags. If your policy includes the first statement without the second statement, the user can't assume the role.
  + The first condition block of this statement allows the user to pass any value for the `CostCenter` and `Project` session tags. You do this by using wildcards (\$1) for the tag value in the policy, which requires that you use the [StringLike](reference_policies_elements_condition_operators.md#Conditions_String) condition operator.
  + The second condition block allows the user to pass only the `Engineering` or `Marketing` value for the `Department` session tag.
  + The third condition block lists the maximum set of tags you can set as transitive. The user can choose to set a subset or no tags as transitive. They cannot set additional tags as transitive. You can require that they set at least one of the tags as transitive by adding another condition block that includes `"Null":{"sts:TransitiveTagKeys":"false"}`. 

## Passing session tags using AssumeRole
AssumeRole

The `AssumeRole` operation returns a set of temporary credentials you can use to access AWS resources. You can use IAM user or role credentials to call `AssumeRole`. To pass session tags while assuming a role, use the `--tags` AWS CLI option or the `Tags` AWS API parameter. 

To set tags as transitive, use the `--transitive-tag-keys` AWS CLI option or the `TransitiveTagKeys` AWS API parameter. Transitive tags persist during role chaining. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).

The following example shows a sample request that uses `AssumeRole`. In this example, when you assume the `my-role-example` role, you create a session named `my-session`. You add the session tag key-value pairs `Project` = `Automation`, `CostCenter` = `12345`, and `Department` = `Engineering`. You also set the `Project` and `Department` tags as transitive by specifying their keys. You must pass a single value for each session tag. AWS STS does not support multi-valued session tags.

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/my-role-example \
--role-session-name my-session \
--tags Key=Project,Value=Automation Key=CostCenter,Value=12345 Key=Department,Value=Engineering \
--transitive-tag-keys Project Department \
--external-id Example987
```

## Passing session tags using AssumeRoleWithSAML
AssumeRoleWithSAML

The `AssumeRoleWithSAML` operation authenticates with SAML-based federation. This operation returns a set of temporary credentials you can use to access AWS resources. For more information about using SAML-based federation for AWS Management Console access, see [Enabling SAML 2.0 federated principals to access the AWS Management Console](id_roles_providers_enable-console-saml.md). For details about AWS CLI or AWS API access, see [SAML 2.0 federation](id_roles_providers_saml.md). For a tutorial on configuring SAML federation for your Active Directory users, see [AWS Federated Authentication with Active Directory Federation Services (ADFS)](https://aws.amazon.com/blogs/security/aws-federated-authentication-with-active-directory-federation-services-ad-fs/) in the AWS Security Blog. 

As an administrator, you can allow members of your company directory to federate into AWS using the AWS STS `AssumeRoleWithSAML` operation. To do this, you must complete the following tasks:

1. [Configure your network as a SAML provider for AWS](id_roles_providers_saml_3rd-party.md).

1. [Create a SAML provider in IAM](id_roles_providers_create_saml.md)

1. [Create a role for SAML 2.0 federation (console)](id_roles_create_for-idp_saml.md)

1. [Finish configuring the SAML IdP and create assertions for the SAML authentication response](id_roles_providers_create_saml_assertions.md)

AWS includes identity providers with certified end-to-end experience for session tags with their identity solutions. To learn how to use these identity providers to configure session tags, see [Integrate third-party SAML solution providers with AWS](id_roles_providers_saml_3rd-party.md).

To pass SAML attributes as session tags, include the `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}`. Use the `AttributeValue` element to specify the value of the tag. Include a separate `Attribute` element for each session tag.

For example, assume that you want to pass the following identity attributes as session tags:
+ `Project:Automation`
+ `CostCenter:12345`
+ `Department:Engineering`

To pass these attributes, include the following elements in your SAML assertion.

**Example snippet of a SAML assertion**  

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/PrincipalTag:Project">
  <AttributeValue>Automation</AttributeValue>
</Attribute>
<Attribute Name="https://aws.amazon.com/SAML/Attributes/PrincipalTag:CostCenter">
  <AttributeValue>12345</AttributeValue>
</Attribute>
<Attribute Name="https://aws.amazon.com/SAML/Attributes/PrincipalTag:Department">
  <AttributeValue>Engineering</AttributeValue>
</Attribute>
```

To set the preceding tags as transitive, include another `Attribute` element with the `Name` attribute set to `https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys`. Transitive tags persist during role chaining. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).

To set the `Project` and `Department` tags as transitive, use the following multi-valued attribute:

**Example snippet of a SAML assertion**  

```
<Attribute Name="https://aws.amazon.com/SAML/Attributes/TransitiveTagKeys">
  <AttributeValue>Project</AttributeValue>
  <AttributeValue>Department</AttributeValue>
</Attribute>
```

## Passing session tags using AssumeRoleWithWebIdentity
AssumeRoleWithWebIdentity

Use OpenID Connect (OIDC)-compliant federation to authenticate the `AssumeRoleWithWebIdentity` operation. This operation returns a set of temporary credentials you can use to access AWS resources. For more information about using web identity federation for AWS Management Console access, see [OIDC federation](id_roles_providers_oidc.md).

To pass session tags from OpenID Connect (OIDC), you must include the session tags in the JSON Web Token (JWT) when you submit the `AssumeRoleWithWebIdentity` request. To learn more about OIDC tokens and claims, see [Using Tokens with User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html) in the *Amazon Cognito Developer Guide*.

AWS supports two claim formats for including session tags in the JWT: 
+ Nested claim format
+ Flattened claim format

### Nested claim format


The nested claim format uses a structure within the `https://aws.amazon.com/tags` namespace in the JWT. In this format:
+ Principal tags are represented as a nested object under the `principal_tags` key.
+ Each principal tag is a single string value.
+ Transitive tag keys are represented in an array under the `transitive_tag_keys` key.
+ Both `principal_tags` and `transitive_tag_keys` are nested under the `https://aws.amazon.com/tags` namespace.

The following example demonstrates a decoded JWT using the nested object format: 

**Example decoded JSON Web Token using the nested claim format**  

```
{
    "sub": "johndoe",
    "aud": "ac_oic_client",
    "jti": "ZYUCeRMQVtqHypVPWAN3VB",
    "iss": "https://xyz.com",
    "iat": 1566583294,
    "exp": 1566583354,
    "auth_time": 1566583292,
    "https://aws.amazon.com/tags": {
        "principal_tags": {
            "Project": ["Automation"],
            "CostCenter": ["987654"],
            "Department": ["Engineering"]
        },
        "transitive_tag_keys": [
            "Project",
            "CostCenter"
        ]
    }
}
```

### Flattened claim format


The flattened claim format is compatible with identity providers that don't support nested objects in JWT claims, such as Microsoft Entra ID. In this format:
+ Principal tags are represented as separate claims with the prefix `https://aws.amazon.com/tags/principal_tags/`. 
+ Each principal tag is a single string value.
+ Transitive tag keys are represented in a single claim as an array of strings with the prefix `https://aws.amazon.com/tags/transitive_tag_keys`.

Now, let's look at how the same information is represented using the flattened claim format:

**Example decoded JSON Web Token using the flattened claim format**  

```
{
    "sub": "johndoe",
    "aud": "ac_oic_client",
    "jti": "ZYUCeRMQVtqHypVPWAN3VB",
    "iss": "https://xyz.com",
    "iat": 1566583294,
    "exp": 1566583354,
    "auth_time": 1566583292,
    "https://aws.amazon.com/tags/principal_tags/Project": "Automation",
    "https://aws.amazon.com/tags/principal_tags/CostCenter": "987654",
    "https://aws.amazon.com/tags/principal_tags/Department": "Engineering",
    "https://aws.amazon.com/tags/transitive_tag_keys": [
        "Project",
        "CostCenter"
    ]
}
```

Both decoded JWT examples show a call to `AssumeRoleWithWebIdentity` with the `Project`, `CostCenter`, and `Department` session tags. Both tokens set the `Project` and `CostCenter` tags as transitive. Transitive tags persist during role chaining. For more information, see [Chaining roles with session tags](#id_session-tags_role-chaining).

The flattened claim format achieves the same result as the nested claim format but uses a flattened structure for tags. It allows you to include session tags in environments where nested JSON objects are not supported in JWT claims. When using either format, ensure that your identity provider is configured to issue tokens with the appropriate claim structures. AWS supports both claim formats, so you can choose the one that best fits your identity provider's specific requirements.

## Passing session tags using GetFederationToken
GetFederationToken

The `GetFederationToken` allows you to federate your user. This operation returns a set of temporary credentials you can use to access AWS resources. To add tags to your federated user session, use the `--tags` AWS CLI option or the `Tags` AWS API parameter. You can't set session tags as transitive when you use `GetFederationToken`, because you can't use the temporary credentials to assume a role. You cannot use role chaining in this case. 

The following example shows a sample request using `GetFederationToken`. In this example, when you request the token, you create a session named `my-fed-user`. You add the session tag key-value pairs `Project` = `Automation` and `Department` = `Engineering`.

**Example GetFederationToken CLI request**  

```
aws sts get-federation-token \
--name my-fed-user \
--tags key=Project,value=Automation key=Department,value=Engineering
```

When you use the temporary credentials returned by the `GetFederationToken` operation, the session principal tags include the user tags and the passed session tags.

## Chaining roles with session tags


You can assume one role and then use the temporary credentials to assume another role. You can continue from session to session. This is called [role chaining](id_roles.md#iam-term-role-chaining). When you pass session tags while assuming a role, you can set the keys as transitive. This ensures that those session tags pass to subsequent sessions in a role chain. You cannot set role tags as transitive. To pass these tags to subsequent sessions, specify them as session tags.

**Note**  
Transitive tags persist during role chaining and replace matching `ResourceTag` values after the evaluation of the role trust policy.

The following example shows how AWS STS passes session tags, transitive tags, and role tags into subsequent sessions in a role chain.

In this example role chaining scenario, you use an IAM user access key in the AWS CLI to assume a role named `Role1`. You then use the resulting session credentials to assume a second role named `Role2`. You can then use the second session credentials to assume a third role named `Role3`. These requests occur as three separate operations. Each role is already tagged in IAM. And during each request, you pass additional session tags.

![\[Role chaining\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/session-tags-chaining-simple.png)


When you chain roles, you can ensure that tags from an earlier session persist to the later sessions. To do this using the `assume-role` CLI command, you must pass the tag as a session tag and set the tag as transitive. You pass the tag `Star` = `1` as a session tag. The command also attaches the tag `Heart` = `1` to the role and applies as a principal tag when you use the session. However, you also want the `Heart` = `1` tag to automatically pass to the second or third session. To do that, you manually include it as a session tag. The resulting session principal tags include both of these tags, and sets them as transitive.

![\[Assuming the first role in a role chain\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/session-tags-chaining-role1.png)


You perform this request using the following AWS CLI command:

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/Role1 \
--role-session-name Session1 \
--tags Key=Star,Value=1 Key=Heart,Value=1 \
--transitive-tag-keys Star Heart
```

You then use the credentials for that session to assume `Role2`. The command attaches the tag `Sun` = `2` to the second role and applies as a principal tag when you use the second session. The `Heart` and `Star` tags inherits the transitive session tags in the first session. The second session resulting principal tags are `Heart` = `1`, `Star` = `1`, and `Sun` = `2`. `Heart` and `Star` continue to be transitive. The `Sun` tag attached to `Role2` is not marked as transitive because it is not a session tag. Future sessions do not inherit this tag. 

![\[Assuming the second role in a role chain\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/session-tags-chaining-role2.png)


You perform this second request using the following AWS CLI command:

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/Role2 \
--role-session-name Session2
```

You then use the second session credentials to assume `Role3`. The principal tags for the third session come from any new session tags, the inherited transitive session tags, and the role tags. The `Heart` = `1` and `Star` = `1` tags on the second session are inherited from the transitive session tag in the first session. If you try to pass the `Sun` = `2` session tag, the operation fails. The inherited `Star` = 1 session tag overrides the role `Star` = `3` tag. In role chaining, the value of a transitive tag overrides the role matching the `ResourceTag` value after the evaluation of the role trust policy. In this example, if `Role3` uses `Star` as a `ResourceTag` in the role trust policy, and sets `ResourceTag` value to the transitive tag value from the calling role session. The role `Lightning` tag also applies to the third session, and not set as transitive.

![\[Assuming the third role in a role chain\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/session-tags-chaining-role3.png)


You perform the third request using the following AWS CLI command:

**Example AssumeRole CLI request**  

```
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/Role3 \
--role-session-name Session3
```

## Using session tags for ABAC


Attribute-based access control (ABAC) uses an authorization strategy that defines permissions based on tag attributes. 

If your company uses an OIDC or SAML-based identity provider (IdP) to manage user identities, you can configure your assertion to pass session tags to AWS. For example, with corporate user identities, when your employees federate into AWS, AWS applies their attributes to their resulting principal. You can then use ABAC to allow or deny permissions based on those attributes. For details, see [IAM tutorial: Use SAML session tags for ABAC](tutorial_abac-saml.md).

For more information about using IAM Identity Center with ABAC, see [Attributes for access control](https://docs.aws.amazon.com/singlesignon/latest/userguide/attributesforaccesscontrol.html) in the *AWS IAM Identity Center User Guide*.

## Viewing session tags in CloudTrail


You can use AWS CloudTrail to view the requests used to assume roles or federate users. The CloudTrail log file includes information about the principal tags for the assumed-role or federated user session. For more information, see [Logging IAM and AWS STS API calls with AWS CloudTrail](cloudtrail-integration.md).

For example, assume that you make an AWS STS `AssumeRoleWithSAML` request, pass session tags, and set those tags as transitive. You can find the following information in your CloudTrail log.

**Example AssumeRoleWithSAML CloudTrail log**  

```
    "requestParameters": {
        "sAMLAssertionID": "_c0046cEXAMPLEb9d4b8eEXAMPLE2619aEXAMPLE",
        "roleSessionName": "MyRoleSessionName",
        "principalTags": {
            "CostCenter": "987654",
            "Project": "Unicorn"
        },
        "transitiveTagKeys": [
            "CostCenter",
            "Project"
        ],
        "durationSeconds": 3600,
        "roleArn": "arn:aws:iam::123456789012:role/SAMLTestRoleShibboleth",
        "principalArn": "arn:aws:iam::123456789012:saml-provider/Shibboleth"
    },
```

You can view the following example CloudTrail logs to view events that use session tags.
+ [Example AWS STS role chaining API event in CloudTrail log file](cloudtrail-integration.md#stscloudtrailexample-assumerole)
+ [Example SAML AWS STS API event in CloudTrail log file](cloudtrail-integration.md#stscloudtrailexample_saml)
+ [Example OIDC AWS STS API event in CloudTrail log file](cloudtrail-integration.md#stscloudtrailexample_web-identity)