Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
使用 Amazon 开发工具包获取具有 Amazon STS 的会话令牌
以下代码示例演示了如何获取具有 Amazon STS 的会话令牌,并将其用于执行需要 MFA 令牌的服务操作。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- CLI
-
- Amazon CLI
-
要获取 IAM 身份的一组短期凭证
以下 get-session-token
命令将检索进行调用的 IAM 身份的一组短期凭证。生成的凭证可用于策略要求多重身份验证(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"
}
}
有关更多信息,请参阅《Amazon IAM 用户指南》中的请求临时安全凭证。
- Python
-
- SDK for Python(Boto3)
-
通过传递 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)
有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。