AWS STS Python(Boto3)SDK용 사용 예제 - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

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

AWS STS Python(Boto3)SDK용 사용 예제

다음 코드 예제에서는 AWS SDK for Python (Boto3) 와 함께 를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다 AWS STS.

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

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

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

작업

다음 코드 예시에서는 AssumeRole을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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 자세한 내용은 AssumeRoleAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 GetSessionToken을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

토큰을 전달하여 세션 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 자세한 내용은 GetSessionTokenAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

시나리오

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

주의

보안 위험을 방지하려면 특별히 제작된 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마세요. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

  • Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 IAM 역할을 생성합니다.

  • MFA 자격 증명이 제공된 경우에만 역할을 수임할 수 있는 권한이 있는 IAM 사용자를 생성합니다.

  • 사용자의 MFA 디바이스를 등록합니다.

  • 역할을 수임하고 임시 보안 인증을 사용하여 S3 버킷을 나열합니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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 자세한 내용은 AssumeRoleAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 현재 계정의 Amazon S3 리소스에 대한 읽기 전용 액세스 권한을 부여하는 IAM 역할을 생성합니다.

  • AWS 페더레이션 엔드포인트에서 보안 토큰을 가져옵니다.

  • 페더레이션 자격 증명으로 콘솔에 액세스하는 데 사용할 수 URL 있는 를 구성합니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

현재 계정의 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 자세한 내용은 AssumeRoleAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

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

주의

보안 위험을 방지하려면 특별히 제작된 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마세요. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

  • Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 IAM 역할을 생성합니다.

  • MFA 자격 증명이 제공된 경우에만 역할을 수임할 수 있는 권한이 있는 IAM 사용자를 생성합니다.

  • 사용자의 MFA 디바이스를 등록합니다.

  • 보안 MFA 인증 정보를 제공하여 세션 토큰을 가져오고 임시 보안 인증을 사용하여 S3 버킷을 나열합니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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 자세한 내용은 GetSessionTokenAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.