

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. [AWS](https://github.com/awsdocs/aws-doc-sdk-examples) 

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS SDKs AWS STS 사용에 대한 코드 예제
<a name="sts_code_examples"></a>

다음 코드 예제에서는 AWS 소프트웨어 개발 키트(SDK)와 AWS Security Token Service 함께를 사용하는 방법을 보여줍니다.

*작업*은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접 호출하는 방법을 보여주며, 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

*시나리오*는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 직접적으로 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

**추가 리소스**
+  **[AWS STS 사용 설명서](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)** -에 대한 자세한 정보입니다 AWS STS.
+ **[AWS STS API 참조](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html)** - 사용 가능한 모든 AWS STS 작업에 대한 세부 정보입니다.
+ **[AWS 개발자 센터](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23iam)** - 범주 또는 전체 텍스트 검색을 기준으로 필터링할 수 있는 코드 예제입니다.
+ **[AWS SDK 예제](https://github.com/awsdocs/aws-doc-sdk-examples)** - 기본 설정 언어로 된 전체 코드가 포함된 GitHub 리포지토리입니다. 코드 설정 및 실행을 위한 지침이 포함되어 있습니다.

**Contents**
+ [기본 사항](sts_code_examples_basics.md)
  + [작업](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)
+ [시나리오](sts_code_examples_scenarios.md)
  + [MFA 토큰이 필요한 IAM 역할 수임](sts_example_sts_Scenario_AssumeRoleMfa_section.md)
  + [페더레이션 사용자를 위해 URL 구성](sts_example_sts_Scenario_ConstructFederatedUrl_section.md)
  + [MFA 토큰이 필요한 세션 토큰 가져오기](sts_example_sts_Scenario_SessionTokenMfa_section.md)

# AWS SDKs AWS STS 사용에 대한 기본 예제
<a name="sts_code_examples_basics"></a>

다음 코드 예제에서는 AWS Security Token Service SDKs에서의 기본 사항을 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 사용을 위해 역할과 연결된 명명된 프로파일을 설정할 수 있습니다. 프로파일을 사용하면 AWS CLI가 assume-role을 호출하고 자격 증명을 관리합니다. 자세한 내용은 [AWS CLI 사용 설명서의 CLI에서 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: cmdlet을 실행하는 데 사용되는 사용자 자격 증명과 연결된 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 참조(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: cmdlet을 실행하는 데 사용되는 사용자 자격 증명과 연결된 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 토큰을 사용하여 인증됩니다. 사용자가 수행할 수 있는 작업을 추가로 제한하기 위해 두 가지 추가 정책이 세션에 적용됩니다. 반환된 자격 증명은 생성되고 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으로 식별된 역할과 연결된 액세스 정책을 수임합니다. 필요에 따라 액세스 권한을 더욱 세분화하는 -Policy 파라미터에 JSON 정책을 전달할 수 있습니다. 역할과 연결된 권한에서 사용 가능한 것보다 더 많은 권한을 부여할 수는 없습니다. -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 Cmdlet 참조(V4)의 [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: Login with Amazon ID 제공업체를 통해 인증된 사용자에 대해 1시간 동안 유효한 임시 자격 증명 세트를 반환합니다. 자격 증명은 역할 ARN으로 식별된 역할과 연결된 액세스 정책을 수임합니다. 필요에 따라 액세스 권한을 더욱 세분화하는 -Policy 파라미터에 JSON 정책을 전달할 수 있습니다. 역할과 연결된 권한에서 사용 가능한 것보다 더 많은 권한을 부여할 수는 없습니다. -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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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)를 참조하세요.

------

# AWS SDKs AWS STS 사용 시나리오
<a name="sts_code_examples_scenarios"></a>

다음 코드 예제에서는 AWS SDKs를 사용하여에서 AWS STS 일반적인 시나리오를 구현하는 방법을 보여줍니다. 이러한 시나리오에서는 내부 AWS STS 또는 다른 함수와 결합된 여러 함수를 호출하여 특정 작업을 수행하는 방법을 보여줍니다 AWS 서비스. 각 시나리오에는 전체 소스 코드에 대한 링크가 포함되어 있습니다. 여기에서 코드를 설정 및 실행하는 방법에 대한 지침을 찾을 수 있습니다.

시나리오는 컨텍스트에 맞는 서비스 작업을 이해하는 데 도움이 되도록 중급 수준의 경험을 대상으로 합니다.

**Topics**
+ [MFA 토큰이 필요한 IAM 역할 수임](sts_example_sts_Scenario_AssumeRoleMfa_section.md)
+ [페더레이션 사용자를 위해 URL 구성](sts_example_sts_Scenario_ConstructFederatedUrl_section.md)
+ [MFA 토큰이 필요한 세션 토큰 가져오기](sts_example_sts_Scenario_SessionTokenMfa_section.md)

# AWS SDK를 AWS STS 사용하여에서 MFA 토큰이 필요한 IAM 역할 수임
<a name="sts_example_sts_Scenario_AssumeRoleMfa_section"></a>

다음 코드 예제에서는 MFA 토큰이 필요한 역할을 수임하는 방법을 보여줍니다.

**주의**  
보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마세요. 대신 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)과 같은 자격 증명 공급자를 통한 페더레이션을 사용하세요.
+ Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 IAM 역할을 생성합니다.
+ MFA 자격 증명이 제공된 경우에만 역할을 수임할 권한이 있는 IAM 사용자를 생성합니다.
+ 사용자를 위한 MFA 디바이스를 등록합니다.
+ 역할을 수임하고 임시 자격 증명을 사용하여 S3 버킷을 나열합니다.

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

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
IAM 사용자를 생성하고, MFA 디바이스를 등록하고, S3 버킷을 나열할 수 있는 권한을 부여하는 역할을 생성합니다. 사용자는 역할을 수임할 수 있는 권한만 있습니다.  

```
def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates a new virtual MFA device.
    Displays the QR code to seed the device.
    Asks for two codes from the MFA device.
    Registers the MFA device for the user.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role and requires MFA.
    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.

    For demonstration purposes, the user is created in the same account as the role,
    but in practice the user would likely be from another account.

    Any MFA device that can scan a QR code will work with this demonstration.
    Common choices are mobile apps like LastPass Authenticator,
    Microsoft Authenticator, or Google Authenticator.

    :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, virtual MFA device, and role.
    """
    user = iam_resource.create_user(UserName=unique_name("user"))
    print(f"Created user {user.name}.")

    virtual_mfa_device = iam_resource.create_virtual_mfa_device(
        VirtualMFADeviceName=unique_name("mfa")
    )
    print(f"Created virtual MFA device {virtual_mfa_device.serial_number}")

    print(
        f"Showing the QR code for the device. Scan this in the MFA app of your "
        f"choice."
    )
    with open("qr.png", "wb") as qr_file:
        qr_file.write(virtual_mfa_device.qr_code_png)
    webbrowser.open(qr_file.name)

    print(f"Enter two consecutive code from your MFA device.")
    mfa_code_1 = input("Enter the first code: ")
    mfa_code_2 = input("Enter the second code: ")
    user.enable_mfa(
        SerialNumber=virtual_mfa_device.serial_number,
        AuthenticationCode1=mfa_code_1,
        AuthenticationCode2=mfa_code_2,
    )
    os.remove(qr_file.name)
    print(f"MFA device is registered with the user.")

    user_key = user.create_access_key_pair()
    print(f"Created access key pair for user.")

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    role = iam_resource.create_role(
        RoleName=unique_name("role"),
        AssumeRolePolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {"AWS": user.arn},
                        "Action": "sts:AssumeRole",
                        "Condition": {"Bool": {"aws:MultiFactorAuthPresent": True}},
                    }
                ],
            }
        ),
    )
    print(f"Created role {role.name} that requires MFA.")

    policy = iam_resource.create_policy(
        PolicyName=unique_name("policy"),
        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.")

    user.create_policy(
        PolicyName=unique_name("user-policy"),
        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."
    )

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, virtual_mfa_device, role
```
MFA 토큰 없이 역할을 수임하는 것은 허용되지 않음을 보여줍니다.  

```
def try_to_assume_role_without_mfa(assume_role_arn, session_name, sts_client):
    """
    Shows that attempting to assume the role without sending MFA credentials results
    in an AccessDenied error.

    :param assume_role_arn: The Amazon Resource Name (ARN) of the role to assume.
    :param session_name: The name of the STS session.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    print(f"Trying to assume the role without sending MFA credentials...")
    try:
        sts_client.assume_role(RoleArn=assume_role_arn, RoleSessionName=session_name)
        raise RuntimeError("Expected AccessDenied error.")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Got AccessDenied.")
        else:
            raise
```
S3 버킷을 나열할 수 있는 권한을 부여하는 역할을 수임하여 필요한 MFA 토큰을 전달하고 버킷을 나열할 수 있음을 보여줍니다.  

```
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)
```
데모용으로 생성된 리소스를 삭제합니다.  

```
def teardown(user, virtual_mfa_device, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    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}.")
    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.")
    for mfa in user.mfa_devices.all():
        mfa.disassociate()
    virtual_mfa_device.delete()
    user.delete()
    print(f"Deleted {user.name}.")
```
이전에 정의한 함수를 사용하여 이 시나리오를 실행합니다.  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(
        f"Welcome to the AWS Security Token Service assume role demo, "
        f"starring multi-factor authentication (MFA)!"
    )
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user, user_key, virtual_mfa_device, role = setup(iam_resource)
    print(f"Created {user.name} and {role.name}.")
    try:
        sts_client = boto3.client(
            "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
        )
        try_to_assume_role_without_mfa(role.arn, "demo-sts-session", sts_client)
        mfa_totp = input("Enter the code from your registered MFA device: ")
        list_buckets_from_assumed_role_with_mfa(
            role.arn,
            "demo-sts-session",
            virtual_mfa_device.serial_number,
            mfa_totp,
            sts_client,
        )
    finally:
        teardown(user, virtual_mfa_device, role)
        print("Thanks for watching!")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)를 참조하세요.

------

# AWS SDK를 사용하여 페더레이션 사용자를 AWS STS 위해 로 URL 구성
<a name="sts_example_sts_Scenario_ConstructFederatedUrl_section"></a>

다음 코드 예제에서는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
+ 현재 계정의 Amazon S3 리소스에 대한 읽기 전용 액세스 권한을 부여하는 IAM 역할을 생성합니다.
+  AWS 페더레이션 엔드포인트에서 보안 토큰을 가져옵니다.
+ 페더레이션형 자격 증명으로 콘솔에 액세스하는 데 사용할 수 있는 URL을 구성합니다.

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

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
현재 계정의 S3 리소스에 대한 읽기 전용 액세스 권한을 부여하는 역할을 생성합니다.  

```
def setup(iam_resource):
    """
    Creates a role that can be assumed by the current user.
    Attaches a policy that allows only Amazon S3 read-only access.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) instance
                         that has the permission to create a role.
    :return: The newly created role.
    """
    role = iam_resource.create_role(
        RoleName=unique_name("role"),
        AssumeRolePolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {"AWS": iam_resource.CurrentUser().arn},
                        "Action": "sts:AssumeRole",
                    }
                ],
            }
        ),
    )
    role.attach_policy(PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess")
    print(f"Created role {role.name}.")

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return role
```
 AWS 페더레이션 엔드포인트에서 보안 토큰을 가져오고 페더레이션 자격 증명으로 콘솔에 액세스하는 데 사용할 수 있는 URL을 구성합니다.  

```
def construct_federated_url(assume_role_arn, session_name, issuer, sts_client):
    """
    Constructs a URL that gives federated users direct access to the AWS Management
    Console.

    1. Acquires temporary credentials from AWS Security Token Service (AWS STS) that
       can be used to assume a role with limited permissions.
    2. Uses the temporary credentials to request a sign-in token from the
       AWS federation endpoint.
    3. Builds a URL that can be used in a browser to navigate to the AWS federation
       endpoint, includes the sign-in token for authentication, and redirects to
       the AWS Management Console with permissions defined by the role that was
       specified in step 1.

    :param assume_role_arn: The role that specifies the permissions that are granted.
                            The current user must have permission to assume the role.
    :param session_name: The name for the STS session.
    :param issuer: The organization that issues the URL.
    :param sts_client: A Boto3 STS instance that can assume the role.
    :return: The federated URL.
    """
    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.")

    session_data = {
        "sessionId": temp_credentials["AccessKeyId"],
        "sessionKey": temp_credentials["SecretAccessKey"],
        "sessionToken": temp_credentials["SessionToken"],
    }
    aws_federated_signin_endpoint = "https://signin.aws.amazon.com/federation"

    # Make a request to the AWS federation endpoint to get a sign-in token.
    # The requests.get function URL-encodes the parameters and builds the query string
    # before making the request.
    response = requests.get(
        aws_federated_signin_endpoint,
        params={
            "Action": "getSigninToken",
            "SessionDuration": str(datetime.timedelta(hours=12).seconds),
            "Session": json.dumps(session_data),
        },
    )
    signin_token = json.loads(response.text)
    print(f"Got a sign-in token from the AWS sign-in federation endpoint.")

    # Make a federated URL that can be used to sign into the AWS Management Console.
    query_string = urllib.parse.urlencode(
        {
            "Action": "login",
            "Issuer": issuer,
            "Destination": "https://console.aws.amazon.com/",
            "SigninToken": signin_token["SigninToken"],
        }
    )
    federated_url = f"{aws_federated_signin_endpoint}?{query_string}"
    return federated_url
```
데모용으로 생성된 리소스를 삭제합니다.  

```
def teardown(role):
    """
    Removes all resources created during setup.

    :param role: The demo role.
    """
    for attached in role.attached_policies.all():
        role.detach_policy(PolicyArn=attached.arn)
        print(f"Detached {attached.policy_name}.")
    role.delete()
    print(f"Deleted {role.name}.")
```
이전에 정의한 함수를 사용하여 이 시나리오를 실행합니다.  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the AWS Security Token Service federated URL demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    role = setup(iam_resource)
    sts_client = boto3.client("sts")
    try:
        federated_url = construct_federated_url(
            role.arn, "AssumeRoleDemoSession", "example.org", sts_client
        )
        print(
            "Constructed a federated URL that can be used to connect to the "
            "AWS Management Console with role-defined permissions:"
        )
        print("-" * 88)
        print(federated_url)
        print("-" * 88)
        _ = input(
            "Copy and paste the above URL into a browser to open the AWS "
            "Management Console with limited permissions. When done, press "
            "Enter to clean up and complete this demo."
        )
    finally:
        teardown(role)
        print("Thanks for watching!")
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)를 참조하세요.

------

# AWS SDK를 AWS STS 사용하여에서 MFA 토큰이 필요한 세션 토큰 가져오기
<a name="sts_example_sts_Scenario_SessionTokenMfa_section"></a>

다음 코드 예제에서는 MFA 토큰이 필요한 세션 토큰을 가져오는 방법을 보여줍니다.

**주의**  
보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마세요. 대신 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)과 같은 자격 증명 공급자를 통한 페더레이션을 사용하세요.
+ Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 IAM 역할을 생성합니다.
+ MFA 자격 증명이 제공된 경우에만 역할을 수임할 권한이 있는 IAM 사용자를 생성합니다.
+ 사용자를 위한 MFA 디바이스를 등록합니다.
+ MFA 자격 증명을 제공하여 세션 토큰을 가져오고 임시 자격 증명을 사용하여 S3 버킷을 나열합니다.

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

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
IAM 사용자를 생성하고, MFA 디바이스를 등록하고, MFA 자격 증명이 사용될 때만 사용자가 S3 버킷을 나열할 수 있는 권한을 부여하는 역할을 생성합니다.  

```
def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates a new virtual multi-factor authentication (MFA) device.
    Displays the QR code to seed the device.
    Asks for two codes from the MFA device.
    Registers the MFA device for the user.
    Creates an access key pair for the user.
    Creates an inline policy for the user that lets the user list Amazon S3 buckets,
    but only when MFA credentials are used.

    Any MFA device that can scan a QR code will work with this demonstration.
    Common choices are mobile apps like LastPass Authenticator,
    Microsoft Authenticator, or Google Authenticator.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, MFA devices, and
                         policies in the account.
    :return: The newly created user, user key, and virtual MFA device.
    """
    user = iam_resource.create_user(UserName=unique_name("user"))
    print(f"Created user {user.name}.")

    virtual_mfa_device = iam_resource.create_virtual_mfa_device(
        VirtualMFADeviceName=unique_name("mfa")
    )
    print(f"Created virtual MFA device {virtual_mfa_device.serial_number}")

    print(
        f"Showing the QR code for the device. Scan this in the MFA app of your "
        f"choice."
    )
    with open("qr.png", "wb") as qr_file:
        qr_file.write(virtual_mfa_device.qr_code_png)
    webbrowser.open(qr_file.name)

    print(f"Enter two consecutive code from your MFA device.")
    mfa_code_1 = input("Enter the first code: ")
    mfa_code_2 = input("Enter the second code: ")
    user.enable_mfa(
        SerialNumber=virtual_mfa_device.serial_number,
        AuthenticationCode1=mfa_code_1,
        AuthenticationCode2=mfa_code_2,
    )
    os.remove(qr_file.name)
    print(f"MFA device is registered with the user.")

    user_key = user.create_access_key_pair()
    print(f"Created access key pair for user.")

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    user.create_policy(
        PolicyName=unique_name("user-policy"),
        PolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "s3:ListAllMyBuckets",
                        "Resource": "arn:aws:s3:::*",
                        "Condition": {"Bool": {"aws:MultiFactorAuthPresent": True}},
                    }
                ],
            }
        ),
    )
    print(
        f"Created an inline policy for {user.name} that lets the user list buckets, "
        f"but only when MFA credentials are present."
    )

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, virtual_mfa_device
```
MFA 토큰을 전달하여 임시 세션 자격 증명을 가져오고 자격 증명을 사용하여 계정에 대한 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)
```
데모용으로 생성된 리소스를 삭제합니다.  

```
def teardown(user, virtual_mfa_device):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo MFA device.
    """
    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.")
    for mfa in user.mfa_devices.all():
        mfa.disassociate()
    virtual_mfa_device.delete()
    user.delete()
    print(f"Deleted {user.name}.")
```
이전에 정의한 함수를 사용하여 이 시나리오를 실행합니다.  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(
        f"Welcome to the AWS Security Token Service assume role demo, "
        f"starring multi-factor authentication (MFA)!"
    )
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user, user_key, virtual_mfa_device = setup(iam_resource)
    try:
        sts_client = boto3.client(
            "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
        )
        try:
            print("Listing buckets without specifying MFA credentials.")
            list_buckets_with_session_token_with_mfa(None, None, sts_client)
        except ClientError as error:
            if error.response["Error"]["Code"] == "AccessDenied":
                print("Got expected AccessDenied error.")
        mfa_totp = input("Enter the code from your registered MFA device: ")
        list_buckets_with_session_token_with_mfa(
            virtual_mfa_device.serial_number, mfa_totp, sts_client
        )
    finally:
        teardown(user, virtual_mfa_device)
        print("Thanks for watching!")
```
+  API 세부 정보는 [AWS SDK for Python (Boto3) API 참조](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/GetSessionToken)의 *GetSessionToken*을 참조하세요.

------