Get Cognito user pool identity in Lambda function

白昼怎懂夜的黑 提交于 2019-11-30 23:45:49
Ravenscar

It depends on if you have Use Lambda Proxy Integration selected in the Integration Request for the lambda. If you have it set then all the token's claims will be passed through on event.requestContext.authorizer.claims.

If you are not using Lambda Proxy Integration then you need to use a Body Mapping Template in the Integration Request for the lambda. An example template with the application/json Content-Type is:

"context" : {
    "sub" : "$context.authorizer.claims.sub",
    "username" : "$context.authorizer.claims['cognito:username']",
    "email" : "$context.authorizer.claims.email",
    "userId" : "$context.authorizer.claims['custom:userId']"
}

This is expecting that there is a custom attribute called userId in the User Pool of course, and they are readable by the client.

You cannot use the id token against the aws cognito-idp APIs, you need to use the access token. You can however use AdminGetUser call with the username, if your lambda is authorized.

Use the event.requestContext.authorizer.claims.sub to get user's Cognito identity sub, which is basically their ID. This assumes you're using Proxy Integration with API Gateway and Lambda.

Here's a simple example using Node; should be similar across other SDKs.

exports.handler = async (event, context, callback) => {
    let cognitoIdentity = event.requestContext.authorizer.claims.sub

    // do something with `cognitoIdentity` here

    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*"
        },        
        body: JSON.stringify("some data for user"),
    };
    return response;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!