0

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

需要一个基于用户名和密码的登录方式,所以用户必须经过身份验证才能被授权上传文件。我创建了一个用户池身份池,这是我想要遵循的模式: 在此处输入图像描述

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

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_tokenIdentity Pool获取临时凭据。

4

1 回答 1

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 调用。

于 2022-01-02T06:23:11.963 回答