LiLian
LiLian

Reputation: 289

How to pass cognito authentication token in the headers through api gateway to a lambda function

I am working on a full-stack project. And I use AWS cognito to do the Authentication part. And on my front-end, I can get the idToken successfully and put into the method headers. Here is the get method code:

          Axios.get(`url`, {
                headers: {
                    'Authorization': Token
                }
            })

On the backend, I use AWS api gateway and lambda. As I understand, if I want to get the token in the lamdba, I have to set up the mapping template in the Integration Request of APIgateway. So here is what I write, but I can't get the idToken. Anyone knows the correct way to get the idToken?

{
  
  "idToken":"$context.authorizer.claims.authorization"
}

Upvotes: 4

Views: 4587

Answers (2)

lindsaymacvean
lindsaymacvean

Reputation: 4527

I still struggled with this when using a node lambda function to grab the user details of the user accessing the apiGateway which was all configured using the sam template.yml

Here is my solution:

Set up my template.yml

GetMethod:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/getMethod.js
      Handler: getMethod.handler
      Runtime: nodejs14.x
      Timeout: 60
      Policies:
         - DynamoDBReadPolicy:
            TableName: !Ref SomeTable
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /some/path
            Method: get
            Auth:
              Authorizer: SomeApiCognitoAuthorizer
            RestApiId:
              Ref: SomeApiGateway
SomeApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: {Get this from cognito}
      Cors: #"'*'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
        AllowMethods: "'GET,PUT,POST,OPTIONS'"
        AllowOrigin: "'*'"
      Auth:
        Authorizers:
          SomeApiCognitoAuthorizer:
            UserPoolArn: 
              - {Get this from the cognito settings}
            Identity: 
              Header: "Authorization"

Then set up the Lambda Function src/getMethod.js

exports.handler = async(event, context) => {
  console.log(event.requestContext.authorizer.claims);
}

Run deploy

sam package --template-file template.yml --output-template-file package.yml --s3-bucket {BLAH} --region eu-west-1 --profile {aws profile}
sam deploy --template-file package.yml --stack-name {BLAH} --capabilities CAPABILITY_IAM --region eu-west-1 --profile {aws profile}

Then go check cloudwatch on the Function

Upvotes: 0

LiLian
LiLian

Reputation: 289

I close this question by myself. After my search, if you use AWS Auth cognit and you want to get the properties in the token, please refer to this doc:

idToken palyload https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html api gateway mapping template: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference.

ex: if you want to get the userName from the id token, on the mapping template, it should be:

{
    "userName" : "$context.authorizer.claims['cognito:username']"
}

Upvotes: 3

Related Questions