AWS STS contoh menggunakan SDK untuk Python (Boto3) - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

AWS STS contoh menggunakan SDK untuk Python (Boto3)

Contoh kode berikut menunjukkan cara melakukan tindakan dan mengimplementasikan skenario umum dengan menggunakan AWS SDK for Python (Boto3) with AWS STS.

Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.

Skenario adalah contoh kode yang menunjukkan kepada Anda bagaimana menyelesaikan tugas tertentu dengan memanggil beberapa fungsi dalam layanan atau dikombinasikan dengan yang lain Layanan AWS.

Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.

Tindakan

Contoh kode berikut menunjukkan cara menggunakanAssumeRole.

SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Asumsikan IAM peran yang memerlukan MFA token dan gunakan kredensil sementara untuk mencantumkan bucket Amazon S3 untuk akun tersebut.

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)
  • Untuk API detailnya, lihat AssumeRole AWSSDKReferensi Python (Boto3). API

Contoh kode berikut menunjukkan cara menggunakanGetSessionToken.

SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Dapatkan token sesi dengan meneruskan MFA token dan gunakan untuk mencantumkan bucket Amazon S3 untuk akun tersebut.

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)

Skenario

Contoh kode berikut menunjukkan bagaimana untuk mengambil peran yang membutuhkan MFA token.

Awas

Untuk menghindari risiko keamanan, jangan gunakan IAM pengguna untuk otentikasi saat mengembangkan perangkat lunak yang dibuat khusus atau bekerja dengan data nyata. Sebaliknya, gunakan federasi dengan penyedia identitas seperti AWS IAM Identity Center.

  • Buat IAM peran yang memberikan izin untuk mencantumkan bucket Amazon S3.

  • Buat IAM pengguna yang memiliki izin untuk mengambil peran hanya ketika MFA kredensyal disediakan.

  • Daftarkan MFA perangkat untuk pengguna.

  • Asumsikan peran dan gunakan kredensyal sementara untuk membuat daftar bucket S3.

SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat IAM pengguna, daftarkan MFA perangkat, dan buat peran yang memberikan izin untuk membuat daftar bucket S3. Pengguna hanya memiliki hak untuk mengambil peran.

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

Tunjukkan bahwa mengasumsikan peran tanpa MFA token tidak diperbolehkan.

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

Asumsikan peran yang memberikan izin untuk mencantumkan bucket S3, meneruskan MFA token yang diperlukan, dan tunjukkan bahwa bucket dapat dicantumkan.

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)

Hancurkan sumber daya yang dibuat untuk demo.

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}.")

Jalankan skenario ini dengan menggunakan fungsi yang ditentukan sebelumnya.

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!")
  • Untuk API detailnya, lihat AssumeRole AWSSDKReferensi Python (Boto3). API

Contoh kode berikut ini menunjukkan cara:

  • Buat IAM peran yang memberikan akses hanya-baca ke sumber daya Amazon S3 akun saat ini.

  • Dapatkan token keamanan dari titik akhir AWS federasi.

  • Membangun sebuah URL yang dapat digunakan untuk mengakses konsol dengan kredenal federasi.

SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat peran yang memberikan akses hanya-baca ke sumber daya S3 akun saat ini.

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

Dapatkan token keamanan dari titik akhir AWS federasi dan buat URL yang dapat digunakan untuk mengakses konsol dengan kredensi federasi.

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

Hancurkan sumber daya yang dibuat untuk demo.

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}.")

Jalankan skenario ini dengan menggunakan fungsi yang ditentukan sebelumnya.

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!")
  • Untuk API detailnya, lihat AssumeRole AWSSDKReferensi Python (Boto3). API

Contoh kode berikut menunjukkan cara mendapatkan token sesi yang membutuhkan MFA token.

Awas

Untuk menghindari risiko keamanan, jangan gunakan IAM pengguna untuk otentikasi saat mengembangkan perangkat lunak yang dibuat khusus atau bekerja dengan data nyata. Sebaliknya, gunakan federasi dengan penyedia identitas seperti AWS IAM Identity Center.

  • Buat IAM peran yang memberikan izin untuk mencantumkan bucket Amazon S3.

  • Buat IAM pengguna yang memiliki izin untuk mengambil peran hanya ketika MFA kredensyal disediakan.

  • Daftarkan MFA perangkat untuk pengguna.

  • Berikan MFA kredensil untuk mendapatkan token sesi dan gunakan kredensil sementara untuk membuat daftar bucket S3.

SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat IAM pengguna, daftarkan MFA perangkat, dan buat peran yang memberikan izin agar pengguna mencantumkan bucket S3 hanya jika MFA kredensil digunakan.

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

Dapatkan kredenal sesi sementara dengan meneruskan MFA token, dan gunakan kredensialnya untuk mencantumkan bucket S3 untuk akun tersebut.

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)

Hancurkan sumber daya yang dibuat untuk demo.

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}.")

Jalankan skenario ini dengan menggunakan fungsi yang ditentukan sebelumnya.

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!")