amazon-web-services - 设置 MFA 后,使用 boto3 访问 aws dynamodb。获取客户端错误
问题描述
以前,当我没有将 MFA 设置为登录 AWS 控制台时,我通过以下方式连接到 dynamodb
dynamo = boto3.resource('dynamodb',
region_name='ap-northeast-2',
endpoint_url='http://dynamodb.ap-northeast-2.amazonaws.com')
table = dynamo.Table('tablename')
并且查询该表非常好。
response = table.query(
KeyConditionExpression =Key("user_id").eq(123123)
)
在我设置 MFA 以获得额外的安全性以登录 AWS 控制台后,现在当我执行上述代码时,我得到:
ClientError: An error occurred (UnrecognizedClientException) when calling the Query operation: The security token included in the request is invalid.
我为 RDB 使用隧道,是否有类似的东西可以用来连接到 dynamodb,或者我需要权限才能访问 dynamodb?
解决方案
当您启用 MFA 时,SDK不会自动知道如何使用它。您的常规 IAM 用户的 API 和 SECRET 密钥已经不够用了。相反,您需要使用仅为您的 MFA 会话创建的临时凭证。
要使 MFA 与 boto3 一起工作,您必须显式调用get_session_token:
启用 MFA 的 IAM 用户需要调用 GetSessionToken并提交与其 MFA 设备关联的 MFA 代码。使用从调用返回的临时安全凭证,IAM 用户可以对需要 MFA 身份验证的 API 操作进行编程调用。
使用get_session_token
您可以调用sts
服务,该服务将根据您的 MFA 详细信息为您提供临时凭证:
sts = boto3.client('sts')
mfa_response = sts.get_session_token(
DurationSeconds=123,
SerialNumber='string',
TokenCode='string'
)
该调用将返回mfa_response
可用于创建新 boto3 会话的凭据。例如:
mfa_session = boto3.session.Session(
aws_access_key_id=mfa_session['Credentials']['AccessKeyId'],
aws_secret_access_key=mfa_session['Credentials']['SecretAccessKey'],
aws_session_token=mfa_session['Credentials']['SessionToken'])
dynamo = mfa_session.resource('dynamodb', ...)
# and the rest of the code
推荐阅读
- python - 映射嵌套列表中的对应元素
- python - 如何读取包含字符串的数据帧,这些字符串最初是 Python/Pandas 中的数组?
- powerbi - DAX 去除过滤器与所有
- sql-server - 根据当前行中另一列的参数,从表达式更新所有行中具有不同值的列
- python - Pandas Dataframe 的递归字典
- c# - 之后检索所有内容?在查询字符串中
- python - 无法更新 anaconda -Error Corrupted Environment
- amazon-web-services - AWS 连接实例已删除
- docker - 有没有办法在 docker swarm 中运行备用服务?
- php - Wordpress:循环内的 preg_replace 仅偶尔有效