0
votes

I need to add AWS API gateway custom authorizer to a Lambda function. Currently I have added the authorizer for each endpoint. As in the following serverless.yml.

serverless.yml

service: test-service

provider:
    name: aws
    runtime: nodejs6.10
    stage: dev
    region: us-east-1

functions:
    bff:
        handler: app.handler
        events:
            - http:
                path: /home
                method: get
                cors: true
                authorizer :
                    arn: arn:aws:lambda:us-east-1:xxxxxx:function:token-verifier
                    resultTtlInSeconds: 0
                    identitySource: method.request.header.Authorization
                    identityValidationExpression: '.*'

How can I add the custom authorizer to the entire lambda function rather than adding separately to each endpoint?

1

1 Answers

7
votes

You're confusing the boundary between AWS API Gateway and AWS Lambda. It's not your fault. Serverless Framework is that good that it almost blurs those two things.


Strictly speaking, AWS Lambda Functions DO NOT need custom authorizers.

Authorizers are used for securing API Gateway endpoints NOT for AWS Lambda functions.

Therefore, you need to define the authorizer for each endpoint you need to require authorization for.


If you're after making your serverless.yml more concise by not repeating the authorizer definition multiple times, you can define it once and just reference it in your endpoints.

service: test-service

custom:
    authorizer:
        arn: arn:aws:lambda:us-east-1:xxxxxx:function:token-verifier
        resultTtlInSeconds: 0
        identitySource: method.request.header.Authorization
        identityValidationExpression: '.*'

provider:
    name: aws
    runtime: nodejs6.10
    stage: dev
    region: us-east-1

functions:
    bff:
        handler: app.handler
        events:
            - http:
                path: /home
                method: get
                cors: true
                authorizer: ${self:custom.authorizer}