Search code examples
aws-lambdamicroservicesserverlesslambda-authorizer

Using lambda authorizer in serverless function exposed through API gateway


I have written a lambda authorizer which returns response in this format -

{
principalId: 123345,
policyDocument: {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Allow",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/verifyToken-stage/GET/"
    }
  ]
}
}

Note- My authorizer's name is verifyToken

In my different microservice(i.e Activity Logs) serverless.yml file I am calling it like this -


service: activity-logs

frameworkVersion: '2'

resources:
  Resources:
    GatewayResponseUnauthorized:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
          gatewayresponse.header.Access-Control-Allow-Methods: "'*'"
          gatewayresponse.header.Access-Control-Allow-Credentials: "'true'"
        ResponseType: UNAUTHORIZED
        RestApiId: 
          Ref: 'ApiGatewayRestApi'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  region: us-east-1
  stage:  ${opt:stage}
functions:
  getActivityLogs:
    handler: handler.getActivityLogs
    environment:
      NODE_ENV:  ${opt:env}
    timeout: 800
    events:
      - http:
          path: /{user_id}
          method: get
          authorizer: arn:aws:lambda:us-east-1:123456789012:function:auth-${opt:stage}-verifyToken
          cors: true
    vpc:
      securityGroupIds:
        - sg-xxxxxxxx
        - sg-xxxxxxxx
        - sg-xxxxxxxx
        - sg-xxxxxxxx
        - sg-xxxxxxxx
      subnetIds:
        - subnet-xxxxxxxxxxxxxxxxx
        - subnet-xxxxxxxxxxxxxxxxx

I have checked my authorizer separately, it is working and returning 200 with the above response. Similarly, my microservice is working without authorizer. But when authorizer is enabled in getActivityLogs, it is not letting my activity-logs execute a single line


Solution

  • I was using callback for returning response in async function and as per this doc, https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html we can simply return our response if a function is async.