Search code examples
javascriptaws-lambdaaws-api-gatewayaws-java-sdk

Unable to get CognitoIdentityId from Java Lambda Function


I currently have an API Gateway setup to tie in Lambda functions which are written using Java. I'm using the javascript SDK to call the API Gateway endpoints and they are correctly relaying to the Lambda functions. However when I try to access the Cognito Identity ID via:

context.getIdentity()

I get the following response:

lambdainternal.api.LambdaCognitoIdentity@xxxxxx

If I run

context.getIdentity().getIdentityId()

It just returns a empty string in the logger. Not sure what I need to do to get the Identity ID for the user making the request to pass through to the context.

I'm generating the Javascript AWS Api Client via the following:

var apiClient = apigClientFactory.newClient({
                    accessKey: credentials.accessKeyId,
                    secretKey: credentials.secretAccessKey,
                    sessionToken: credentials.sessionToken,
                    region: 'us-east-1'
                });

The lambda functions are secured using IAM policies and the user is able to access the lambda functions so authentication is working correctly. It's just not providing the IdentityId for some reason.


Solution

  • In order for Lambda to access the Cognito identity in its own context variable, you need to enable the checkbox "Invoke with caller credentials" on the Integration Response tab.

    Alternatively, you could also use API Gateway's mapping templates and pass the value of $context.identity.cognitoIdentityId to your Lambda function. The mapping template would look something like this:

    {
      "cognito-identity" : "$context.identity.cognitoIdentityId"
    }
    

    Please also have a look at one of API Gateway's forum discussions for more details / background information (How to pass cognito identity id to backend through API Gateway).