샘플 코드: 멀티 팩터 인증이 포함된 자격 증명 요청하기 - AWS Identity and Access Management

샘플 코드: 멀티 팩터 인증이 포함된 자격 증명 요청하기

다음 예에서는 GetSessionTokenAssumeRole 작업을 호출하고 MFA 인증 파라미터를 전달하는 방법을 보여줍니다. 권한이 없어도 GetSessionToken을 호출할 수 있지만, AssumeRole을 호출할 수 있게 허용하는 정책이 있어야 합니다. 반환된 자격 증명은 계정 내 모든 S3 버킷의 목록을 나열하는 데 사용됩니다.

MFA 인증이 포함된 GetSessionToken 호출하기(Python 및 C#)

AWS SDK for Python (Boto).NET용 AWS SDK를 토대로 작성된 다음 예는 GetSessionToken을 호출하고 MFA 인증 정보를 전달하는 방법을 보여 줍니다. GetSessionToken 작업에서 반환하는 임시 보안 자격 증명은 이어서 계정 내 모든 S3 버킷의 목록을 나열하는 데 사용됩니다.

이 코드를 실행하는 사용자(또는 사용자가 속한 그룹)에게 연결된 정책에서는 반환된 임시 자격 증명에 대한 권한을 제공합니다. 이 예의 경우 정책에서 사용자에게 Amazon S3 ListBuckets 작업을 요청할 수 있는 권한을 부여해야 합니다.

Python 사용하기

import boto from boto.s3.connection import S3Connection from boto.sts import STSConnection # Prompt for MFA time-based one-time password (TOTP) mfa_TOTP = raw_input("Enter the MFA code: ") # The calls to AWS STS GetSessionToken must be signed with the access key ID and secret # access key of an IAM user. The credentials can be in environment variables or in # a configuration file and will be discovered automatically # by the STSConnection() function. For more information, see the Python SDK # documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html sts_connection = STSConnection() # Use the appropriate device ID (serial number for hardware device or ARN for virtual device). # Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values. tempCredentials = sts_connection.get_session_token( duration=3600, mfa_serial_number="&region-arn;iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID", mfa_token=mfa_TOTP ) # Use the temporary credentials to list the contents of an S3 bucket s3_connection = S3Connection( aws_access_key_id=tempCredentials.access_key, aws_secret_access_key=tempCredentials.secret_key, security_token=tempCredentials.session_token ) # Replace BUCKET-NAME with an appropriate value. bucket = s3_connection.get_bucket(bucket_name="BUCKET-NAME") objectlist = bucket.list() for obj in objectlist: print obj.name

C# 사용하기

Console.Write("Enter MFA code: "); string mfaTOTP = Console.ReadLine(); // Get string from user /* The calls to AWS STS GetSessionToken must be signed using the access key ID and secret access key of an IAM user. The credentials can be in environment variables or in a configuration file and will be discovered automatically by the AmazonSecurityTokenServiceClient constructor. For more information, see https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html */ AmazonSecurityTokenServiceClient stsClient = new AmazonSecurityTokenServiceClient(); GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest(); getSessionTokenRequest.DurationSeconds = 3600; // Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values getSessionTokenRequest.SerialNumber = "arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID"; getSessionTokenRequest.TokenCode = mfaTOTP; GetSessionTokenResponse getSessionTokenResponse = stsClient.GetSessionToken(getSessionTokenRequest); // Extract temporary credentials from result of GetSessionToken call GetSessionTokenResult getSessionTokenResult = getSessionTokenResponse.GetSessionTokenResult; string tempAccessKeyId = getSessionTokenResult.Credentials.AccessKeyId; string tempSessionToken = getSessionTokenResult.Credentials.SessionToken; string tempSecretAccessKey = getSessionTokenResult.Credentials.SecretAccessKey; SessionAWSCredentials tempCredentials = new SessionAWSCredentials(tempAccessKeyId, tempSecretAccessKey, tempSessionToken); // Use the temporary credentials to list the contents of an S3 bucket // Replace BUCKET-NAME with an appropriate value ListObjectsRequest S3ListObjectsRequest = new ListObjectsRequest(); S3ListObjectsRequest.BucketName = "BUCKET-NAME"; S3Client = AWSClientFactory.CreateAmazonS3Client(tempCredentials); ListObjectsResponse S3ListObjectsResponse = S3Client.ListObjects(S3ListObjectsRequest); foreach (S3Object s3Object in S3ListObjectsResponse.S3Objects) { Console.WriteLine(s3Object.Key); }

MFA 인증이 포함된 AssumeRole 호출하기(Python)

AWS SDK for Python (Boto)을 토대로 작성된 다음 예는 AssumeRole을 호출하고 MFA 인증 정보를 전달하는 방법을 보여 줍니다. AssumeRole에서 반환한 임시 보안 자격 증명은 계정의 모든 Amazon S3 버킷을 나열하는 데 사용됩니다.

이 시나리오에 대한 자세한 내용은 시나리오: 교차 계정 위임에 대한 MFA 보호를 참조하십시오.

import boto from boto.s3.connection import S3Connection from boto.sts import STSConnection # Prompt for MFA time-based one-time password (TOTP) mfa_TOTP = raw_input("Enter the MFA code: ") # The calls to AWS STS AssumeRole must be signed with the access key ID and secret # access key of an IAM user. (The AssumeRole API operation can also be called using temporary # credentials, but this example does not show that scenario.) # The IAM user credentials can be in environment variables or in # a configuration file and will be discovered automatically # by the STSConnection() function. For more information, see the Python SDK # documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html sts_connection = STSConnection() # Use appropriate device ID (serial number for hardware device or ARN for virtual device) # Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS, ROLE-NAME, and MFA-DEVICE-ID with appropriate values tempCredentials = sts_connection.assume_role( role_arn="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:role/ROLE-NAME", role_session_name="AssumeRoleSession1", mfa_serial_number="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID", mfa_token=mfa_TOTP ) # Use the temporary credentials to list the contents of an S3 bucket s3_connection = S3Connection( aws_access_key_id=tempCredentials.credentials.access_key, aws_secret_access_key=tempCredentials.credentials.secret_key, security_token=tempCredentials.credentials.session_token ) # Replace BUCKET-NAME with a real bucket name bucket = s3_connection.get_bucket(bucket_name="BUCKET-NAME") objectlist = bucket.list() for obj in objectlist: print obj.name