Adding an existing custom Lambda Authorizer to API Gateway with CDK and Python

OK, this is an pretty niche one, but I had to write it up because it annoyed me so much figuring it out. I'm using the Python CDK library, aws_cdk, not the TypeScript interface (but the concepts are the same).

If you have an existing custom Lambda Authorizer, and you want to add it to a new API Gateway LambdaRestApi, you can't just grab the Authorizer with a normal from_XXXX command in the Authorizer CDK class. Such a from_ function doesn't exist for Authorizers, as of CDK 2.20.0.

What you have to do is specify the Lambda function used by the authorizer, using the from_function_name function. You can then create a TokenAuthorizer based on your existing authorizer Lambda, and pass that to your LambdaRestApi, like so:

from aws_cdk import (
aws_lambda,
aws_apigateway)

# ...
# create your stack class, IAM roles, etc

# define some EXECUTION (not auth) Lambda for your API, here we'll call it api_lambda

# grab your existing Lambda auth function from the lambda name
auth_function = aws_lambda.Function.from_function_name(self, "myAuthLambda", "existing_lambda_name")

# New Authorizer based on your existing Lambda
lambda_authorizer = aws_apigateway.TokenAuthorizer(self, "myAuthorizer", handler=auth_function)

# Your new Lambda-backed and authorized API
api = aws_apigateway(self,
        "myEndpoint",
        handler=api_lambda,
        default_method_options={"authorizer": lambda_authorizer, "authorization_type": aws_apigateway.AuthorizationType.CUSTOM})

And that's it! Now you've got an API Gateway that uses a Lambda Authorizer and also a Lambda execution backend.

If you're still running into issues with your specific setup, it's pretty easy to do development testing of your Lambda Authorizers. In the API Gateway console, first go to the endpoint that calls your authorizer, and then click "Authorizers" in the left nav bar. Each Authorizer will have two links at the bottom of their panes: "Edit" and "Test". Clicking "Test" is going to be your best bet at getting actionable logs.

Subscribe to The Cloud Consultant

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe