Define lambda authorizer response format using serverless framework

Viewed 1330

According to this AWS documentation page covering authorizers for AWS API Gateway it is possible to define authorizer as lambda function returning a boolean value in isAuthorized response field to allow/deny the API request.

However after numerous attempts I can't understand how to define it in serverless.yml (or at least in AWS console)

I'm new to AWS and serverless framework. I've decided not to dive into IAM access policies or Cognito just yet, thus I'm trying to build a very simple lambda authorizer function that just yields a boolean value to allow/deny API access.

I have defined my functions section in serverless.yml as follows:

functions:
  add_content:
    handler: src.handler.add
    module: src/handler
    events:
      - http:
          path: /content
          method: post
          authorizer: customAuthorizer
  customAuthorizer:
    handler: src.authorizer.authorize
    module: src/authorizer

The authorizer function is as simple as:

def authorize(event, context):
    response = {"isAuthorized": True}
    return response

However if I try to test it I see the following CloudWatch stacktrace:

Mon May 03 20:06:11 UTC 2021 : Endpoint request body after transformations: {"type":"TOKEN","methodArn":"arn:aws:execute-api:eu-central-1:238758647165:ww9wzq8hp8/ESTestInvoke-stage/GET/","authorizationToken":"123456789"}
Mon May 03 20:06:11 UTC 2021 : Sending request to https://lambda.eu-central-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-central-1:238758647165:function:sls-playground-dev-customAuthorizer/invocations
Mon May 03 20:06:11 UTC 2021 : Authorizer result body before parsing: {"isAuthorized": true}
Mon May 03 20:06:11 UTC 2021 : Execution failed due to configuration error: Invalid JSON in response: Unrecognized field "isAuthorized" , not marked as ignorable
Mon May 03 20:06:11 UTC 2021 : AuthorizerConfigurationException

In addition to that:

  1. When opening API gateway in AWS console I don't have the Develop section as shown in documentation.
  2. If I try to create an auhtorizer manually from AWS console there's no response mode section.

enter image description here

3 Answers

SLS documents this here

You can set properties for your Authorizer response format like this:

authorizer:
    payloadVersion: 2.0
    enableSimpleResponses: true

This will allow isAuthorized:true|false responses

Enable simple responses.

authorizer:
    payloadVersion: 2.0
    enableSimpleResponses: true

Handler should do a callback instead of returning the value.

def authorize(event, context, callback):
    response = {"isAuthorized": True}
    callback(null, response)
Related