Search code examples
amazon-web-servicesaws-api-gatewayamazon-cognito

AWS Lambda - Can't get Cognito user data in lambda function


I am trying to get Cognito user data in a lambda function. I am trying to pass it to lambda using body mapping template as

{
    "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
    "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
    "cognito-identity-id" : "$context.identity.cognitoIdentityId",
    "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
}

But, in the lambda function, the data is coming empty as

'cognito-authentication-provider': '',
'cognito-authentication-type': '',
'cognito-identity-id': '',
'cognito-identity-pool-id': ''

Please help me solve this.

Thanks...

EDIT: Added Cognito authentication dev-dummy-auth as enter image description here


Solution

  • To build on Dilip Kola's answer. It appears that the context variables you are trying to access do not exist for the authorization method you are using.

    The only way I can see to get the token information to the underlying Lambda service is to pass the whole token down and open it in the Lambda with an appropriate library for the language you are using.

    You can pass the token by adding a line to your body mapping template.

    {"Authorization" : "$input.params().header.get('Authorization')"}
    

    A Cognito ID token is in the form of a JWT (JSON Web Token). The ISS claim is in the format https://cognito-idp.{region}.amazonaws.com/{userPoolId}.

    Update - To include information about User Groups

    The Cognito Identity token does not contain the User Groups of the user who was issued the token.

    To restrict API access to individuals in certain User Groups, you will have to change your authentication method to AWS_IAM Authorizer using Cognito Federated Identities.

    An alternative would be to use a custom attribute such as role in Cognito marking certain users as Admin, User, etc (as these can be passed in the id token) then evaluating that custom attribute. If you were going to go down this route, I would move to a Custom Lambda Authorizer method of authentication. This way you can check the custom attributes at the same time you validate the token, so requests don't ever reach the backend if the user does not have the correct access rights.