Creating a Cognito Custom Authorizer Lambda Function

Creating a Cognito Custom Authorizer Lambda Function

by admin March 22, 2020

In this post, we’ll focus on creating a Cognito custom authorizer lambda function. Using the SAM framework to build microservices can be a very powerful paradigm for any organization. By decoupling your application logic, you can enable smaller teams to move fast while utilizing components of the monolithic applications.Commonly, companies want to maintain a central authentication service.

By using a custom authorizer in Lambda, you can utilize the benefits of API Gateway and Cognito with nearly ANY authentication source. You’re also able to cache requests in order to maintain performance.To implement this in code is quite simple. We’ll walk through the bulk of the implementation.

First, we’ll define the authorizer in our template.yaml as below:

        Type: AWS::Serverless::Api
          StageName: dev
            DefaultAuthorizer: LambdaAuthorizer
                FunctionPayloadType: REQUEST
                FunctionArn: !GetAtt AuthFunction.Arn
                    - authorization
                  ReauthorizeEvery: 100

        Type: AWS::Serverless::Function
          CodeUri: src/auth/
          Handler: app.lambda_handler
          Runtime: python3.8


A sample lambda function would look like the following:

import json
import requests
import os

def generate_policy_document(effect, method_arn):
	if effect == None or method_arn == None:
		return None

	policy_document = {
		'Version': '2012-10-17',
		'Statement': [{
			'Action': ['execute-api:Invoke'],
			'Effect': effect,
			'Resource': method_arn

	print("Policy Document:")
	return policy_document

def generate_auth_response(principal_id, effect, method_arn):
	policy_document = generate_policy_document(effect, method_arn)
	return {
		"principalId": principal_id,
		"policyDocument": policy_document
	return policy_document

def lambda_handler(event, context):
	arn = event['methodArn']
	auth_token = event['headers']['Authorization']

	# Make make request to reviewpush endpoint
	response = requests.get(os.environ['AUTH_URL'], headers={'Authorization': auth_token})

	if response.status_code == 200:
		return generate_auth_response('user', 'Allow', arn)
		return generate_auth_response('user', 'Deny', arn)


As a reminder, CORS configuration is important to consider when working with API Gateway. Check out our article on working with API Gateway for more insights on how to implement CORS and avoid potential “gotchas” here.

Want to see a full demo? Check out the source code on Github.

As we’ve recommended, SAM is a powerful AWS framework for building serverless microservices. Using this design pattern, you can extrapolate certain functionality outside of your current monolithic application. All while giving your team the freedom and flexibility to develop faster with higher product quality.

Social Shares

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *