使用 Amazon 开发工具包获取需要具有 Amazon STS 的 MFA 令牌的会话令牌 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包获取需要具有 Amazon STS 的 MFA 令牌的会话令牌

以下代码示例显示了如何:

  • 创建一个 IAM 角色,该角色授予列出 Amazon S3 存储桶的权限。

  • 创建一个 IAM 用户,该用户仅在提供 MFA 凭证时才有权代入角色。

  • 为该用户注册一个 MFA 设备。

  • 提供 MFA 凭证以获取会话令牌,并使用临时凭证列出 S3 存储桶。

Python
适用于 Python (Boto3) 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建一个 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 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 GetSessionToken

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。