首页 > 解决方案 > 设置 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?

标签: amazon-web-servicesamazon-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

推荐阅读