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:
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.
CodePudding user response:
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.