Mapping between Cognito Identity ID and Username

In all of the APIs we use “cognitoIdentityId” (from “event.requestContext.identity.cognitoIdentityId”) for the user reference, like in the chapter “Add a Create Note API” (https://serverless-stack.com/chapters/add-a-create-note-api.html).

I see that if I use Auth.currentUserInfo() from aws-amplify in the client, I get an object containing a username. The same username as I see in the Cognito User Pool table of users.

So my questions are:

  1. What is the difference between Cognito Identity ID and Username? When to use one or another?
  2. How do I map the Cognito Identity ID to a username? If I look up the Cognito Idendity ID in my User Pool table of users, I’m not able to find anything. Here only the username is present. How is it mapped?

Thanks!

Yeah there isn’t a super simple way to get this mapping (at least the last time I checked). We talked about this in some other thread but basically your Lambda functions have the Cognito User Pool User Id) passed to them in the event object.

Here is some sample code:

export async function main(event, context, callback) {
  const authProvider = event.requestContext.identity.cognitoAuthenticationProvider;
  // cognito authentication provider looks like:
  // cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxxxx,cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxxxx:CognitoSignIn:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  const parts = authProvider.split(':');
  const userPoolIdParts = parts[parts.length - 3].split('/');
  const userPoolId = userPoolIdParts[userPoolIdParts.length - 1];
  const userPoolUserId = parts[parts.length - 1];
  ...
}

This id allows you to get any User Pool info in your Lambda function.

Thanks jayair, this was very helpful. I’d been looking for how to find the cognito user id of the current user, and then their cognito email address and other attributes. This code snippet alone could be a complete article (it prob is and I just missed it).

Cheers

1 Like

Good call. I’ll add it to the list.