API Gateway provides an HTTP API endpoint that is fully configurable. You define the HTTP resources (like /user ), the HTTP methods on that resources (like POST , GET , DELETE , …) and the integration (e.g. Lambda function) that should be called to process the request. A Lambda function can then run whatever logic is needed to answer the request. The Lambda function returns its result to the API Gateway. The API Gateway responds to the caller. The following figure demonstrates this flow.

How Custom Authorization works

You could include the authentication and authorization logic into the Lambda function that handles the request. But you can also separate concerns, make use of API Gateway caching mechanism, and go for Custom Authorization. API Gateway will invoke another Lambda function (Auth Lambda Function) for the first request and caches that result for a configurable duration. Caching will reduce the overhead (latency and DynamoDB charges) for authentication and authorization to a minimum.

You can use whatever logic you like to decide if a request is allowed or not. In this blog post, I will implement an API token mechanism. All HTTP requests from clients must pass an Authorization: xyz header. The Auth Lambda Function will take this token to query a DynamoDB table. The request is allowed or denied depending on if the query matches.

As usual in this blog, I will use CloudFormation to setup all the needed resources.

CloudFormation setup

Getting started

The first thing you need is an API Gateway.

"RestApi" : {

"Type" : "AWS::ApiGateway::RestApi" ,

"Properties" : {

"Name" : "Api"

}

}



With the logical group in place, you can continue to add all the necessary parts to your API.

Auth Lambda Function

The code for the Auth Lambda Function is responsible for looking up the token. The Authorization HTTP header field is used to transmit the token. You can use Node.js and the AWS SDK for JavaScript to implement this logic. API Gateway will pass an event to our function like this:

{

"type" : "TOKEN" ,

"authorizationToken" : "<caller-supplied-token>" ,

"methodArn" : "arn:aws:execute-api:<regionId>:<accountId>:<apiId>/<stage>/<method>/<resourcePath>"

}



API Gateway expects that we respond in the following way: