Search code examples
javascriptamazon-s3aws-lambdaamazon-cognitoaws-amplify

How to fetch Amazon Cognito Identity ID (user_identity_id) for the user from the lambda function?


In the Amplify documentation, under the Storage/File access levels section there is a paragraph that states:

Files are stored under private/{user_identity_id}/ where the user_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.

How to fetch user_identity_id from the lambda function?

Request to the lambda is authorized, the event.requestContext.authorizer.claims object is available, I can see the user data, but not the user_identity_id.

EDIT: Now I see that there is a field event.requestContext.identity.cognitoIdentityId, but the value is null. Still need to find the way to fetch it.


Solution

  • Ok, so there's no right way to map Cognito identity ID and Cognito user. There is a lengthy discussion here where a couple of workarounds can be found. For now, I'm going to use this solution where, instead of identity_id, you can specify a custom attribute (most likely a sub) as a folder name.

    EDIT: There is another solution that might help (found somewhere on the internet, and I verified that it works)

    const AWS = require('aws-sdk')
    const cognitoIdentity = new AWS.CognitoIdentity();
    
    function getCognitoIdentityId(jwtToken) {
      const params = getCognitoIdentityIdParams(jwtToken);
      return cognitoIdentity
        .getId(params)
        .promise()
        .then(data => {
          if (data.IdentityId) {
            return data.IdentityId;
          }
          throw new Error('Invalid authorization token.');
        });
    }
    
    function getCognitoIdentityIdParams(jwtToken) {
      const loginsKey = `cognito-idp.${process.env.REGION}.amazonaws.com/${process.env.USERPOOLID}`;
      return {
        IdentityPoolId: `${process.env.IDENTITY_POOL_ID}`,
        Logins: {
          [loginsKey]: jwtToken,
        },
      };
    }