简体   繁体   English

Boto3 - 如何使用 Amazon Cognito 从身份池获取临时凭证以访问 S3 存储桶?

[英]Boto3 - How to use Amazon Cognito to get temporary credentials from Identity Pool to access S3 bucket?

I am developing a python application whose purpose is to upload data to S3.我正在开发一个 python 应用程序,其目的是将数据上传到 S3。 Since it must be installed on different devices independently, I wouldn't want store aws credentials on every platform but I want to create an authentication method based on Amazon Cognito .由于它必须独立安装在不同的设备上,我不希望在每个平台上都存储 aws 凭证,但我想创建一个基于Amazon Cognito的身份验证方法。

It is necessary a login method based on username and password, so the user must be authenticated before being authorized to upload files.需要一个基于用户名和密码的登录方式,所以用户必须经过身份验证才能被授权上传文件。 I've created a Users Pool and Identity Pool and this is the pattern I want to follow:我创建了一个用户池身份池,这是我想要遵循的模式: 在此处输入图像描述

This is the code I wrote to authenticate user:这是我为验证用户而编写的代码:

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"]

But I don't know how to use access_token to get temporary credentials from Identity Pool .但我不知道如何使用access_tokenIdentity Pool获取临时凭据。

Access token isn't what you want here.访问令牌不是您想要的。 You can use the identity token with get_id and get_credentials_for_identity calls to finally get temporary AWS credentials.您可以将身份令牌与 get_id 和 get_credentials_for_identity 调用一起使用,以最终获取临时 AWS 凭证。 For Example:例如:

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 will have access key, secret key and session token. aws_cred 将具有访问密钥、秘密密钥和 session 令牌。 You can use these to sign AWS calls.您可以使用这些来签署 AWS 调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM