Monday, 6 September 2021

How to use AWS API Gateway Android SDK with Cognito Userpool Authorizer?

I'm having trouble to properly use the integration of user pools with the API gateway from my Android app. (As per this documentation http://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)

The API Config

Authorizer for my user pool configured and the method configured to use the authorizer. Body mapping template:

#set($inputRoot = $input.path('$'))
{
          "userid" : "$context.authorizer.claims.sub"
}

The Android App

The following is only a collection of copy and paste snippets since it's scattered across different place in the app.

// init
credentialsProvider = new CognitoCachingCredentialsProvider(
        context,
        IDENTITY_POOL_ID,
        IDENTITY_POOL_REGION);
userPool = new CognitoUserPool(
        context,
        USER_POOL_ID,
        CLIENT_ID,
        CLIENT_SECRET,
        new ClientConfiguration(),
        USER_POOL_REGION);

// login
user = aws.userPool.getUser(username);
user.getSessionInBackground(authHandler);
String token = session.getIdToken().getJWTToken();
Map<String, String> logins = new HashMap<>();
logins.put(USER_POOL_ARN, token);
aws.credentialsProvider.setLogins(logins);
aws.credentialsProvider.refresh();

// using the api
ApiClientFactory factory = new ApiClientFactory().credentialsProvider(
            aws.credentialsProvider);
apiClient = factory.build(MyAPIClient.class);
apiClient.mainGet()

The current result

com.amazonaws.mobileconnectors.apigateway.ApiClientException: {"message":"Unauthorized"}
                                                                 (Service: MyAPIClient; Status Code: 401; Error Code: null; Request ID: cefd713c-1234-1234-1234-b9e32fbdedb0)
                                                                    at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.handleResponse(ApiClientHandler.java:294)
                                                                    at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.invoke(ApiClientHandler.java:111)
                                                                    at java.lang.reflect.Proxy.invoke(Proxy.java:397)
                                                                    at $Proxy2.mainGet(Unknown Source)
                                                                    at com.my.mainGet(my.java:206)

So I can imagine that initializing the credentials provider with an identity pool will lead to a an identity token but I really need a token from the user pool. However that leads me to the question of how do I setup my ApiClient properly to use the user pool token?



from How to use AWS API Gateway Android SDK with Cognito Userpool Authorizer?

No comments:

Post a Comment