

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 [AWS](https://github.com/awsdocs/aws-doc-sdk-examples)

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS SDKs AWS STS を使用するための基本的な例
<a name="sts_code_examples_basics"></a>

次のコード例は、 SDKs AWS Security Token Service で AWS の基本を使用する方法を示しています。

**Contents**
+ [アクション](sts_code_examples_actions.md)
  + [`AssumeRole`](sts_example_sts_AssumeRole_section.md)
  + [`AssumeRoleWithWebIdentity`](sts_example_sts_AssumeRoleWithWebIdentity_section.md)
  + [`DecodeAuthorizationMessage`](sts_example_sts_DecodeAuthorizationMessage_section.md)
  + [`GetFederationToken`](sts_example_sts_GetFederationToken_section.md)
  + [`GetSessionToken`](sts_example_sts_GetSessionToken_section.md)

# AWS SDKs AWS STS を使用するためのアクション
<a name="sts_code_examples_actions"></a>

次のコード例は、 AWS SDKs で個々の AWS STS アクションを実行する方法を示しています。それぞれの例には、GitHub へのリンクがあり、そこにはコードの設定と実行に関する説明が記載されています。

これらの抜粋は AWS STS API を呼び出し、コンテキスト内で実行する必要がある大規模なプログラムからのコード抜粋です。アクションは [AWS SDKs AWS STS を使用するシナリオ](sts_code_examples_scenarios.md) のコンテキスト内で確認できます。

 以下の例には、最も一般的に使用されるアクションのみ含まれています。詳細な一覧については、「[AWS Security Token Service API リファレンス](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html)」を参照してください。

**Topics**
+ [`AssumeRole`](sts_example_sts_AssumeRole_section.md)
+ [`AssumeRoleWithWebIdentity`](sts_example_sts_AssumeRoleWithWebIdentity_section.md)
+ [`DecodeAuthorizationMessage`](sts_example_sts_DecodeAuthorizationMessage_section.md)
+ [`GetFederationToken`](sts_example_sts_GetFederationToken_section.md)
+ [`GetSessionToken`](sts_example_sts_GetSessionToken_section.md)

# AWS SDK または CLI `AssumeRole`で を使用する
<a name="sts_example_sts_AssumeRole_section"></a>

次のサンプルコードは、`AssumeRole` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [MFA トークンを必要とする IAM ロールを割り当てる](sts_example_sts_Scenario_AssumeRoleMfa_section.md) 
+  [フェデレーションユーザー向け URL の作成](sts_example_sts_Scenario_ConstructFederatedUrl_section.md) 

------
#### [ .NET ]

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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}");
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/sts-2011-06-15/AssumeRole)」を参照してください。**

------
#### [ Bash ]

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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
}
```
+  API の詳細については、「AWS CLI  コマンドリファレンス」の「[AssumeRole](https://docs.aws.amazon.com/goto/aws-cli/sts-2011-06-15/AssumeRole)」を参照してください。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForCpp/sts-2011-06-15/AssumeRole)」を参照してください。**

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

**AWS CLI**  
**ロールを引き受けるには**  
次の `assume-role` コマンドは、IAM ロール `s3-access-example` のために短期間有効な認証情報のセットを取得します。  

```
aws sts assume-role \
    --role-arn arn:aws:iam::123456789012:role/xaccounts3access \
    --role-session-name s3-access-example
```
出力:  

```
{
    "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"
    }
}
```
コマンドの出力には、 AWSに対する認証に使用できるアクセスキー、シークレットキー、およびセッショントークンが含まれています。  
 AWS CLI を使用するには、ロールに関連付けられた名前付きプロファイルを設定できます。プロファイルを使用すると、CLI AWS は assume-role を呼び出し、認証情報を管理します。詳細については、「 [CLI ユーザーガイド」の「 CLI AWS で IAM ロール](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html)を使用する」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssumeRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/sts-2011-06-15/AssumeRole)」を参照してください。**

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sts#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
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 });
```
IAM ロールを割り当てます。  

```
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);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[AssumeRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sts/command/AssumeRoleCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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);
    }
  });
}
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sts-2011-06-15/AssumeRole)」を参照してください。**

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: リクエスト元のユーザーが通常アクセスできない AWS リソースにアクセスするために 1 時間使用できる一時的な認証情報 (アクセスキー、シークレットキー、セッショントークン) のセットを返します。返される認証情報には、引き受けているロールのアクセスポリシーと提供されたポリシーで許可されている権限があります (提供されたポリシーを使用して、引き受けているロールのアクセスポリシーで定義されている権限を超える権限を付与することはできません)。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**例 2: 引き受けているロールのアクセスポリシーで定義されているのと同じ権限を持つ、1 時間有効の一時的な認証情報を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**例 3: コマンドレットの実行に使用されるユーザー認証情報に関連付けられている MFA からシリアル番号と生成されたトークンを提供する一時的な認証情報一式を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**例 4: 顧客アカウントで定義されているロールを引き受けた一時的な認証情報一式を返します。第三者が引き受けることができるロールごとに、顧客アカウントは、ロールを引き受けるたび、-ExternalId パラメータで渡す必要がある識別子を使用してロールを作成する必要があります。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssumeRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: リクエスト元のユーザーが通常アクセスできない AWS リソースにアクセスするために 1 時間使用できる一時的な認証情報 (アクセスキー、シークレットキー、セッショントークン) のセットを返します。返される認証情報には、引き受けているロールのアクセスポリシーと提供されたポリシーで許可されている権限があります (提供されたポリシーを使用して、引き受けているロールのアクセスポリシーで定義されている権限を超える権限を付与することはできません)。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**例 2: 引き受けているロールのアクセスポリシーで定義されているのと同じ権限を持つ、1 時間有効の一時的な認証情報を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**例 3: コマンドレットの実行に使用されるユーザー認証情報に関連付けられている MFA からシリアル番号と生成されたトークンを提供する一時的な認証情報一式を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**例 4: 顧客アカウントで定義されているロールを引き受けた一時的な認証情報一式を返します。第三者が引き受けることができるロールごとに、顧客アカウントは、ロールを引き受けるたび、-ExternalId パラメータで渡す必要がある識別子を使用してロールを作成する必要があります。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[AssumeRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
MFA トークンを必要とする IAM ロールを想定し、一時的な認証情報を使用してアカウントの Amazon S3 バケットを一覧表示します。  

```
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)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)」を参照してください。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/sts-2011-06-15/AssumeRole)」を参照してください。**

------
#### [ Rust ]

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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),
    }
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[AssumeRole](https://docs.rs/aws-sdk-sts/latest/aws_sdk_sts/client/struct.Client.html#method.assume_role)」を参照してください。

------
#### [ Swift ]

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](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
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[AssumeRole](https://sdk.amazonaws.com/swift/api/awssts/latest/documentation/awssts/stsclient/assumerole(input:))」を参照してください。

------

# CLI で `AssumeRoleWithWebIdentity` を使用する
<a name="sts_example_sts_AssumeRoleWithWebIdentity_section"></a>

次のサンプルコードは、`AssumeRoleWithWebIdentity` を使用する方法を説明しています。

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

**AWS CLI**  
**ウェブ ID (OAuth 2."0) で認証されたロールの短期認証情報を取得するには**  
次の `assume-role-with-web-identity` コマンドは、IAM ロール `app1` のために短期間有効な認証情報のセットを取得します。リクエストは、指定されたウェブ ID プロバイダーから提供されたウェブ ID トークンを使用して認証されます。ユーザーが実行できることをさらに制限するために、2 つの追加ポリシーがセッションに適用されます。返される認証情報は、生成されてから 1 時間後に失効します。  

```
aws sts assume-role-with-web-identity \
    --duration-seconds 3600 \
    --role-session-name "app1" \
    --provider-id "www.amazon.com" \
    --policy-arns "arn:aws:iam::123456789012:policy/q=webidentitydemopolicy1","arn:aws:iam::123456789012:policy/webidentitydemopolicy2" \
    --role-arn arn:aws:iam::123456789012:role/FederatedWebIdentityRole \
    --web-identity-token "Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ"
```
出力:  

```
{
    "SubjectFromWebIdentityToken": "amzn1.account.AF6RHO7KZU5XRVQJGXK6HB56KR2A",
    "Audience": "client.5498841531868486423.1548@apps.example.com",
    "AssumedRoleUser": {
        "Arn": "arn:aws:sts::123456789012:assumed-role/FederatedWebIdentityRole/app1",
        "AssumedRoleId": "AROACLKWSDQRAOEXAMPLE:app1"
    },
    "Credentials": {
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
        "Expiration": "2020-05-19T18:06:10+00:00"
    },
    "Provider": "www.amazon.com"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssumeRoleWithWebIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role-with-web-identity.html)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: Login with Amazon ID プロバイダーで認証されたユーザーの一時的な認証情報一式 (1 時間有効) を返します。認証情報は、ロール ARN によって識別されるロールに関連付けられたアクセスポリシーを引き受けます。オプションで、JSON ポリシーを-Policy パラメータに渡して、アクセス権限をさらに絞り込むことができます (ロールに関連付けられている権限で使用可能な権限よりも多くの権限を付与することはできません)。-WebIdentityToken に渡される値は、ID プロバイダーから返された一意のユーザー識別子です。**  

```
Use-STSWebIdentityRole -DurationInSeconds 3600 -ProviderId "www.amazon.com" -RoleSessionName "app1" -RoleArn "arn:aws:iam::123456789012:role/FederatedWebIdentityRole" -WebIdentityToken "Atza...DVI0r1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: Login with Amazon ID プロバイダーで認証されたユーザーの一時的な認証情報一式 (1 時間有効) を返します。認証情報は、ロール ARN によって識別されるロールに関連付けられたアクセスポリシーを引き受けます。オプションで、JSON ポリシーを-Policy パラメータに渡して、アクセス権限をさらに絞り込むことができます (ロールに関連付けられている権限で使用可能な権限よりも多くの権限を付与することはできません)。-WebIdentityToken に渡される値は、ID プロバイダーから返された一意のユーザー識別子です。**  

```
Use-STSWebIdentityRole -DurationInSeconds 3600 -ProviderId "www.amazon.com" -RoleSessionName "app1" -RoleArn "arn:aws:iam::123456789012:role/FederatedWebIdentityRole" -WebIdentityToken "Atza...DVI0r1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# CLI で `DecodeAuthorizationMessage` を使用する
<a name="sts_example_sts_DecodeAuthorizationMessage_section"></a>

次のサンプルコードは、`DecodeAuthorizationMessage` を使用する方法を説明しています。

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

**AWS CLI**  
**リクエストへの応答として返されるエンコードされた認可メッセージをデコードするには**  
次の `decode-authorization-message` の例では、Amazon Web Services リクエストへの応答として返されるエンコードされたメッセージから、リクエストの承認ステータスに関する追加情報をデコードします。  

```
aws sts decode-authorization-message \
    --encoded-message EXAMPLEWodyRNrtlQARDip-eTA6i6DrlUhHhPQrLWB_lAbl5pAKxl9mPDLexYcGBreyIKQC1BGBIpBKr3dFDkwqeO7e2NMk5j_hmzAiChJN-8oy3EwiCjkUW5fdRNjcRvscGlUo_MhqHqHpR-Ojau7BMjOTWwOtHPhV_Zaz87yENdipr745EjQwRd5LaoL3vN8_5ZfA9UiBMKDgVh1gjqZJFUiQoubv78V1RbHNYnK44ElGKmUWYa020I1y6TNS9LXoNmc62GzkfGvoPGhD13br5tXEOo1rAm3vsPewRDFNkYL-4_1MWWezhRNEpqvXBDXLI9xEux7YYkRtjd45NJLFzZynBUubV8NHOevVuighd1Mvz3OiA-1_oPSe4TBtjfN9s7kjU1z70WpVbUgrLVp1xXTK1rf9Ea7t8shPd-3VzKhjS5tLrweFxNOKwV2GtT76B_fRp8HTYz-pOu3FZjwYStfvTb3GHs3-6rLribGO9jZOktkfE6vqxlFzLyeDr4P2ihC1wty9tArCvvGzIAUNmARQJ2VVWPxioqgoqCzMaDMZEO7wkku7QeakEVZdf00qlNLMmcaVZb1UPNqD-JWP5pwe_mAyqh0NLw-r1S56YC_90onj9A80sNrHlI-tIiNd7tgNTYzDuPQYD2FMDBnp82V9eVmYGtPp5NIeSpuf3fOHanFuBZgENxZQZ2dlH3xJGMTtYayzZrRXjiq_SfX9zeBbpCvrD-0AJK477RM84vmtCrsUpJgx-FaoPIb8LmmKVBLpIB0iFhU9sEHPqKHVPi6jdxXqKaZaFGvYVmVOiuQdNQKuyk0p067POFrZECLjjOtNPBOZCcuEKEXAMPLE
```
出力:  

```
{
    "DecodedMessage": "{\"allowed\":false,\"explicitDeny\":true,\"matchedStatements\":{\"items\":[{\"statementId\":\"VisualEditor0\",\"effect\":\"DENY\",\"principals\":{\"items\":[{\"value\":\"AROA123456789EXAMPLE\"}]},\"principalGroups\":{\"items\":[]},\"actions\":{\"items\":[{\"value\":\"ec2:RunInstances\"}]},\"resources\":{\"items\":[{\"value\":\"*\"}]},\"conditions\":{\"items\":[]}}]},\"failures\":{\"items\":[]},\"context\":{\"principal\":{\"id\":\"AROA123456789EXAMPLE:Ana\",\"arn\":\"arn:aws:sts::111122223333:assumed-role/Developer/Ana\"},\"action\":\"RunInstances\",\"resource\":\"arn:aws:ec2:us-east-1:111122223333:instance/*\",\"conditions\":{\"items\":[{\"key\":\"ec2:MetadataHttpPutResponseHopLimit\",\"values\":{\"items\":[{\"value\":\"2\"}]}},{\"key\":\"ec2:InstanceMarketType\",\"values\":{\"items\":[{\"value\":\"on-demand\"}]}},{\"key\":\"aws:Resource\",\"values\":{\"items\":[{\"value\":\"instance/*\"}]}},{\"key\":\"aws:Account\",\"values\":{\"items\":[{\"value\":\"111122223333\"}]}},{\"key\":\"ec2:AvailabilityZone\",\"values\":{\"items\":[{\"value\":\"us-east-1f\"}]}},{\"key\":\"ec2:ebsOptimized\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:IsLaunchTemplateResource\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:InstanceType\",\"values\":{\"items\":[{\"value\":\"t2.micro\"}]}},{\"key\":\"ec2:RootDeviceType\",\"values\":{\"items\":[{\"value\":\"ebs\"}]}},{\"key\":\"aws:Region\",\"values\":{\"items\":[{\"value\":\"us-east-1\"}]}},{\"key\":\"ec2:MetadataHttpEndpoint\",\"values\":{\"items\":[{\"value\":\"enabled\"}]}},{\"key\":\"aws:Service\",\"values\":{\"items\":[{\"value\":\"ec2\"}]}},{\"key\":\"ec2:InstanceID\",\"values\":{\"items\":[{\"value\":\"*\"}]}},{\"key\":\"ec2:MetadataHttpTokens\",\"values\":{\"items\":[{\"value\":\"required\"}]}},{\"key\":\"aws:Type\",\"values\":{\"items\":[{\"value\":\"instance\"}]}},{\"key\":\"ec2:Tenancy\",\"values\":{\"items\":[{\"value\":\"default\"}]}},{\"key\":\"ec2:Region\",\"values\":{\"items\":[{\"value\":\"us-east-1\"}]}},{\"key\":\"aws:ARN\",\"values\":{\"items\":[{\"value\":\"arn:aws:ec2:us-east-1:111122223333:instance/*\"}]}}]}}}"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[ポリシーの評価論理](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecodeAuthorizationMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/decode-authorization-message.html)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: リクエストへの応答として返された、指定されたエンコード済みメッセージコンテンツに含まれる追加情報をデコードします。承認ステータスの詳細は、アクションをリクエストしたユーザーが見てはならない特権情報である可能性があるため、追加情報はエンコードされます。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: リクエストへの応答として返された、指定されたエンコード済みメッセージコンテンツに含まれる追加情報をデコードします。承認ステータスの詳細は、アクションをリクエストしたユーザーが見てはならない特権情報である可能性があるため、追加情報はエンコードされます。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# CLI で `GetFederationToken` を使用する
<a name="sts_example_sts_GetFederationToken_section"></a>

次のサンプルコードは、`GetFederationToken` を使用する方法を説明しています。

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

**AWS CLI**  
**IAM ユーザーアクセスキー認証情報を使用して一時的なセキュリティ認証情報一式を返すには**  
次の `get-federation-token` の例では、ユーザーの一時的なセキュリティ認証情報一式 (アクセスキー ID、シークレットアクセスキー、セキュリティトークンで構成) を返します。IAM ユーザーの長期的なセキュリティ認証情報を使用して、`GetFederationToken` オペレーションを呼び出す必要があります。  

```
aws sts get-federation-token \
    --name Bob \
    --policy file://myfile.json \
    --policy-arns arn=arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess \
    --duration-seconds 900
```
`myfile.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "elasticloadbalancing:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:ListMetrics",
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:Describe*"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "autoscaling:Describe*",
            "Resource": "*"
        }
    ]
}
```
出力:  

```
{
    "Credentials": {
        "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "SessionToken": "EXAMPLEpZ2luX2VjEGoaCXVzLXdlc3QtMiJIMEYCIQC/W9pL5ArQyDD5JwFL3/h5+WGopQ24GEXweNctwhi9sgIhAMkg+MZE35iWM8s4r5Lr25f9rSTVPFH98G42QQunWMTfKq0DCOP//////////wEQAxoMNDUyOTI1MTcwNTA3Igxuy3AOpuuoLsk3MJwqgQPg8QOd9HuoClUxq26wnc/nm+eZLjHDyGf2KUAHK2DuaS/nrGSEXAMPLE",
        "Expiration": "2023-12-20T02:06:07+00:00"
    },
    "FederatedUser": {
        "FederatedUserId": "111122223333:Bob",
        "Arn": "arn:aws:sts::111122223333:federated-user/Bob"
    },
    "PackedPolicySize": 36
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFederationToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-federation-token.html)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: 「Bob」をフェデレーションユーザーの名前として使用して、1 時間有効なフェデレーショントークンをリクエストします。この名前は、リソースベースのポリシー (Amazon S3 バケットポリシーなど) のフェデレーションユーザー名を参照するために使用できます。提供される JSON 形式の IAM ポリシーを使用して、IAM ユーザーが利用できるアクセス権限の範囲を絞り込みます。指定されたポリシーでは、リクエストしたユーザーに付与されたアクセス権限よりも多くのアクセス権限を付与することはできません。フェデレーションユーザーの最終的なアクセス権限は、渡されたポリシーと IAM ユーザーポリシーの共通部分に基づいて最も制限の厳しい一式となります。**  

```
Get-STSFederationToken -Name "Bob" -Policy "...JSON policy..." -DurationInSeconds 3600
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetFederationToken](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: 「Bob」をフェデレーションユーザーの名前として使用して、1 時間有効なフェデレーショントークンをリクエストします。この名前は、リソースベースのポリシー (Amazon S3 バケットポリシーなど) のフェデレーションユーザー名を参照するために使用できます。提供される JSON 形式の IAM ポリシーを使用して、IAM ユーザーが利用できるアクセス権限の範囲を絞り込みます。指定されたポリシーでは、リクエストしたユーザーに付与されたアクセス権限よりも多くのアクセス権限を付与することはできません。フェデレーションユーザーの最終的なアクセス権限は、渡されたポリシーと IAM ユーザーポリシーの共通部分に基づいて最も制限の厳しい一式となります。**  

```
Get-STSFederationToken -Name "Bob" -Policy "...JSON policy..." -DurationInSeconds 3600
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetFederationToken](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# AWS SDK または CLI `GetSessionToken`で を使用する
<a name="sts_example_sts_GetSessionToken_section"></a>

次のサンプルコードは、`GetSessionToken` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [MFA トークンを必要とするセッショントークンの取得](sts_example_sts_Scenario_SessionTokenMfa_section.md) 

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

**AWS CLI**  
**IAM ID のために短期間有効な認証情報のセットを取得するには**  
次の `get-session-token` コマンドは、呼び出しを実行する IAM ID のために短期間有効な認証情報のセットを取得します。結果として得られる認証情報は、ポリシーによって多要素認証 (MFA) が必要とされるリクエストのために使用できます。認証情報は生成されてから 15 分後に失効します。  

```
aws sts get-session-token \
    --duration-seconds 900 \
    --serial-number "YourMFADeviceSerialNumber" \
    --token-code 123456
```
出力:  

```
{
    "Credentials": {
        "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
        "Expiration": "2020-05-19T18:06:10+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSessionToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-session-token.html)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: 一定期間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。一時的な認証情報をリクエストするために使用される認証情報は、現在のシェルのデフォルトから推測されます。他の認証情報を指定するには、-ProfileName または-AccessKey/-SecretKey パラメータを使用します。**  

```
Get-STSSessionToken
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 2: 1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。リクエストを行うために使用される認証情報は、指定されたプロファイルから取得されます。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 3: プロファイル「myprofilename」で認証情報が指定されているアカウントに関連付けられた MFA デバイスの識別番号とデバイスから提供された値を使用して、1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSessionToken](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: 一定期間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。一時的な認証情報をリクエストするために使用される認証情報は、現在のシェルのデフォルトから推測されます。他の認証情報を指定するには、-ProfileName または-AccessKey/-SecretKey パラメータを使用します。**  

```
Get-STSSessionToken
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 2: 1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。リクエストを行うために使用される認証情報は、指定されたプロファイルから取得されます。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 3: プロファイル「myprofilename」で認証情報が指定されているアカウントに関連付けられた MFA デバイスの識別番号とデバイスから提供された値を使用して、1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[GetSessionToken](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
MFA トークンを渡してセッショントークンを取得し、それを使用してアカウントの Amazon S3 バケットを一覧表示します。  

```
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)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetSessionToken](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/GetSessionToken)」を参照してください。

------