0

I am developing a python application whose purpose is to upload data to 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.

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: enter image description here

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.

1 Answers1

2

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. 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. You can use these to sign AWS calls.

Ninad Gaikwad
  • 4,272
  • 2
  • 13
  • 23
  • Thanks! I assume that inside Login param there is the user pool id, but I have a question: what is 'id_tok' and how I can get it? – Sante Altamura Jan 02 '22 at 09:07
  • 1
    You already have it. You get it using client.initiate_auth(). Currently you are using access token. Just find Identity token instead. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.initiate_auth – Ninad Gaikwad Jan 03 '22 at 06:57