2023-09-03 16:51:25+00:00

In web-scale architectures, some API endpoints perform computationally expensive operations (like triggering web crawlers or running legacy database queries). If these endpoints are left unsecured or exposed to the public internet, bad actors can easily run up massive AWS bills or scrape your price books.

To protect these services, we route all calls through AWS API Gateway secured by Custom Lambda Authorizers that validate incoming JSON Web Tokens (JWTs) before routing the request to downstream handlers.


1. Custom Lambda Authorizers

When an API call hits API Gateway with an Authorization: Bearer header, the gateway forwards the token to an authorizer Lambda. This function decodes the JWT using public keys, checks the expiry, and verifies user scopes. If valid, it returns an IAM Policy allowing the request:

# Minimal IAM Policy generator in Python Lambda
def generate_iam_policy(principal_id, effect, resource_arn):
    return {
        "principalId": principal_id,
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "execute-api:Invoke",
                    "Effect": effect,
                    "Resource": resource_arn
                }
            ]
        }
    }

2. Rate Limiting and Quota Allocations

By defining API Usage Plans in API Gateway, we assign specific request rates and monthly quotas to different client IDs (e.g., separating internal webhooks from university partners), protecting downstream systems from spikes.

Caching IAM Policy Documents in AWS API Gateway Lambda Authorizers

Configure a 300-second authorizer result TTL keyed on the bearer token hash so valid client requests do not invoke the custom Lambda authorizer on every single API call.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs