【问题标题】:Boto3 - How to use Amazon Cognito to get temporary credentials from Identity Pool to access S3 bucket?Boto3 - 如何使用 Amazon Cognito 从身份池获取临时凭证以访问 S3 存储桶?
【发布时间】:2022-01-01 19:40:38
【问题描述】:

我正在开发一个 python 应用程序,其目的是将数据上传到 S3。由于它必须独立安装在不同的设备上,我不希望在每个平台上都存储 aws 凭证,但我想创建一个基于 Amazon Cognito 的身份验证方法。

需要一个基于用户名和密码的登录方式,所以用户必须认证才能授权上传文件。 我创建了 Users PoolIdentity Pool,这是我想要遵循的模式:

这是我为验证用户而编写的代码:

import os
import boto3

username = "user1997"
password = "abcd1234!!"

client = boto3.client("cognito-idp", region_name="ap-south-1")
response = client.initiate_auth(
    ClientId=os.getenv("COGNITO_USER_CLIENT_ID"),
    AuthFlow="USER_PASSWORD_AUTH",
    AuthParameters={"USERNAME": username, "PASSWORD": password},
)
access_token = response["AuthenticationResult"]["AccessToken"]

但我不知道如何使用access_token身份池获取临时凭据。

【问题讨论】:

    标签: amazon-s3 boto3 amazon-cognito aws-userpools aws-identitypools


    【解决方案1】:

    访问令牌不是您想要的。您可以将身份令牌与 get_id 和 get_credentials_for_identity 调用一起使用,以最终获取临时 AWS 凭证。例如:

    identityId = identity.get_id(
            IdentityPoolId='us-east-1:xyxyxyxy-ab23-9989-7767-776x7676f5',
            Logins={
                'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxx': id_tok
            }
        )['IdentityId']
    aws_cred = identity.get_credentials_for_identity(
            IdentityId=identityId,
            Logins={
                'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxx': id_tok
            }
        )['Credentials']
    

    aws_cred 将具有访问密钥、密钥和会话令牌。您可以使用这些来签署 AWS 调用。

    【讨论】:

    • 谢谢!我假设登录参数内部有用户池 id,但我有一个问题:什么是 'id_tok' 以及如何获取它?
    • 你已经拥有了。您可以使用 client.initiate_auth() 获取它。目前您正在使用访问令牌。只需找到身份令牌即可。 boto3.amazonaws.com/v1/documentation/api/latest/reference/…
    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多