Search code examples
amazon-web-servicesamazon-cognito

Get Temporary Credentials from Application Load Balancer ALB Cognito Authentication


Trying to get temporary credentials after performing Cognito authentication in an AWS Application Load Balancer (ALB). I've run into a road block following these AWS docs.

The Application Load Balancer authenticates the user and only passes access tokens and claims to the backend but does not pass the ID token information.

Without the ID token, is there a way to get temporary credentials from an identity pool (via code below)? Can I access an identity pool via the access token (which is in the headers)?

import boto3

provider_name = "cognito-idp.{region}.amazonaws.com/{user_pool_id}"
id_token = ""  # how do I get this from access token or load balancer ???

client = boto3.client("cognito-identity")
get_id_response = client.get_id(
    IdentityPoolId=identity_pool_id,
    Logins={provider_name: id_token}
)
get_credentials_for_identity_response = client.get_credentials_for_identity(
    IdentityId=get_id_response['IdentityId'],
    Logins={provider_name: id_token}
)
credentials = get_credentials_for_identity_response["Credentials"]

Solution

  • Unfortunately not.

    While the documentation you linked to has a lot of useful information, the key excerpt is the following (emphasis mine):

    The load balancer adds the following HTTP headers:

    • x-amzn-oidc-accesstoken The access token from the token endpoint, in plain text.

    • x-amzn-oidc-identity The subject field (sub) from the user info endpoint, in plain text.

    Note: The sub claim is the best way to identify a given user.

    • x-amzn-oidc-data The user claims, in JSON web tokens (JWT) format.

    These tokens follow the JWT format but are not ID tokens.

    This means that, at best, you can expect an Access Token - and even then the documentation warns

    Standard libraries are not compatible with the padding that is included in the Application Load Balancer authentication token in JWT format.

    You can obtain the user's identifier from the sub property of the token, along with the user's username claim. Based on this it would be possible to use the admin-get-user function to obtain the Cognito user reference, but the admin-initiate-auth function still requires either a USERNAME and PASSWORD (for --auth-flow ADMIN_USER_PASSWORD_AUTH or USERNAME and SRP_A (for --auth-flow USER_SRP_AUTH).

    Both of these need you to supply authentication credentials which you will not have purely from the headers of the current user - you'd have to ask them to authenticate again, which defeats the entire purpose of the Cognito integration on your load balancer.

    TL;DR - As you've correctly identified, without a valid OAuth ID token you will not be able to obtain STS credentials for a Cognito Identity Pool via the get_id function.