StackPractices
advanced By Mathias Paulenko

Secure API Gateway with Custom Lambda Authorizers

Implement custom Lambda authorizers for API Gateway with JWT validation, IAM policy generation, and caching for token-based authentication in serverless APIs.

Overview

A Lambda authorizer sits between API Gateway and your handler: it sees the request first, checks the token, and answers with an IAM policy that says Allow or Deny. Authentication stays out of your business logic, and the approach works with any token format — JWT, OAuth, or something custom. Below: a JWT authorizer, IAM policy generation, passing context to handlers, caching, and the request/response authorizer types.

When to Use This

  • Serverless APIs with custom authentication — JWT, OAuth, or API keys backed by a database lookup
  • Fine-grained access control per route or HTTP method
  • Integrating third-party identity providers like Auth0, Cognito, or Okta
  • Any API Gateway + Lambda setup that validates tokens

Prerequisites

  • Python 3.11+
  • API Gateway (REST or HTTP API)
  • PyJWT package for JWT validation

Solution

1. JWT Lambda Authorizer (Request Type)

import json
import jwt
import time
import os

JWT_SECRET = os.environ['JWT_SECRET']
JWT_ALGORITHM = 'HS256'

def lambda_handler(event, context):
    try:
        token = extract_token(event)
        claims = validate_jwt(token)

        principal_id = claims['sub']
        policy = generate_policy(
            principal_id=principal_id,
            effect='Allow',
            resource=event['routeArn'],
            context={
                'userId': principal_id,
                'email': claims.get('email', ''),
                'role': claims.get('role', 'user'),
            },
        )
        return policy

    except Exception as e:
        print(f"Authorization failed: {e}")
        return generate_policy(
            principal_id='unauthorized',
            effect='Deny',
            resource=event['routeArn'],
            context={},
        )

def extract_token(event: dict) -> str:
    headers = event.get('headers', {})
    auth_header = headers.get('Authorization') or headers.get('authorization', '')

    if not auth_header.startswith('Bearer '):
        raise ValueError("Missing or invalid Authorization header")

    return auth_header[7:]

def validate_jwt(token: str) -> dict:
    try:
        claims = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        if claims.get('exp', 0) < time.time():
            raise ValueError("Token expired")
        return claims
    except jwt.InvalidTokenError as e:
        raise ValueError(f"Invalid token: {e}")

def generate_policy(principal_id: str, effect: str, resource: str, context: dict) -> dict:
    return {
        'principalId': principal_id,
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [
                {
                    'Action': 'execute-api:Invoke',
                    'Effect': effect,
                    'Resource': resource,
                }
            ],
        },
        'context': context,
    }

2. SAM Template with Authorizer

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  AuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: authorizer.lambda_handler
      Runtime: python3.11
      CodeUri: src/
      Environment:
        Variables:
          JWT_SECRET: '{{resolve:secretsmanager:jwt-secret:SecretString}}'

  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.lambda_handler
      Runtime: python3.11
      CodeUri: src/

  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Auth:
        DefaultAuthorizer: JwtAuthorizer
        Authorizers:
          JwtAuthorizer:
            FunctionArn: !GetAtt AuthFunction.Arn
            Identity:
              Header: Authorization
              ValidationExpression: ^Bearer [a-zA-Z0-9._-]+$
            AuthorizerResultTtlInSeconds: 300

  ProtectedResource:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.lambda_handler
      Runtime: python3.11
      CodeUri: src/
      Events:
        GetUsers:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /users
            Method: GET
            Auth:
              Authorizer: JwtAuthorizer

3. Access Authorizer Context in Handler

import json

def lambda_handler(event, context):
    # Authorizer context is available in the event
    auth_context = event.get('requestContext', {}).get('authorizer', {})

    user_id = auth_context.get('userId', 'unknown')
    email = auth_context.get('email', 'unknown')
    role = auth_context.get('role', 'user')

    if role != 'admin':
        return {
            'statusCode': 403,
            'body': json.dumps({'error': 'Insufficient permissions'}),
        }

    return {
        'statusCode': 200,
        'body': json.dumps({
            'message': f'Hello {email}',
            'userId': user_id,
        }),
    }

4. Role-Based Access Control

import json
import jwt
import os

JWT_SECRET = os.environ['JWT_SECRET']

def lambda_handler(event, context):
    try:
        token = extract_token(event)
        claims = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
        role = claims.get('role', 'user')
        method = event['httpMethod']
        resource = event['routeArn']

        # Define role-based permissions
        permissions = {
            'admin': ['GET', 'POST', 'PUT', 'DELETE'],
            'editor': ['GET', 'POST', 'PUT'],
            'user': ['GET'],
        }

        allowed_methods = permissions.get(role, [])

        if method in allowed_methods:
            return generate_policy(claims['sub'], 'Allow', resource, {
                'userId': claims['sub'],
                'role': role,
            })
        else:
            return generate_policy(claims['sub'], 'Deny', resource, {
                'userId': claims['sub'],
                'role': role,
            })

    except Exception as e:
        print(f"Auth error: {e}")
        return generate_policy('error', 'Deny', event['routeArn'], {})

def generate_policy(principal_id, effect, resource, context):
    return {
        'principalId': principal_id,
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': effect,
                'Resource': resource,
            }],
        },
        'context': context,
    }

def extract_token(event):
    headers = event.get('headers', {})
    auth_header = headers.get('Authorization') or headers.get('authorization', '')
    if not auth_header.startswith('Bearer '):
        raise ValueError("Missing Authorization header")
    return auth_header[7:]

5. Authorizer with Database Lookup (API Key)

import json
import os
import boto3
import hashlib

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['API_KEYS_TABLE'])

def lambda_handler(event, context):
    api_key = event.get('headers', {}).get('x-api-key', '')

    if not api_key:
        return generate_deny(event['routeArn'], 'Missing API key')

    # Hash the API key for lookup
    key_hash = hashlib.sha256(api_key.encode()).hexdigest()

    response = table.get_item(Key={'apiKeyHash': key_hash})

    if 'Item' not in response:
        return generate_deny(event['routeArn'], 'Invalid API key')

    item = response['Item']

    # Check if key is active
    if item.get('status') != 'active':
        return generate_deny(event['routeArn'], 'API key inactive')

    # Check rate limits or quotas
    tier = item.get('tier', 'free')

    return generate_allow(
        principal_id=item['clientId'],
        resource=event['routeArn'],
        context={
            'clientId': item['clientId'],
            'tier': tier,
        },
    )

def generate_allow(principal_id, resource, context):
    return {
        'principalId': principal_id,
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Allow',
                'Resource': resource,
            }],
        },
        'context': context,
    }

def generate_deny(resource, reason):
    return {
        'principalId': 'unauthorized',
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Deny',
                'Resource': resource,
            }],
        },
        'context': {'denyReason': reason},
    }

6. Caching Configuration

# Authorizer caching — TTL in seconds
# Responses are cached by the Identity header value (the Authorization header)
Auth:
  DefaultAuthorizer: JwtAuthorizer
  Authorizers:
    JwtAuthorizer:
      FunctionArn: !GetAtt AuthFunction.Arn
      Identity:
        Header: Authorization
        ValidationExpression: ^Bearer .+$
      AuthorizerResultTtlInSeconds: 300  # Cache for 5 minutes
sequenceDiagram diagram: participant C as Client

How It Works

  1. Request flow: the client sends a request with an Authorization header. API Gateway intercepts it and invokes the authorizer Lambda with the token and the route ARN.
  2. Token validation: the authorizer verifies signature, expiry, and claims, then emits an IAM policy — Effect: Allow when the token checks out, Effect: Deny when it doesn’t.
  3. IAM policy: in the response, Resource carries the ARN of the route the client asked for (execute-api:Invoke on arn:aws:execute-api:...). API Gateway reads that policy — Allow goes through to your handler, Deny ends in a 403.
  4. Context passing: whatever you put in the context object of the authorizer response shows up in the handler at event.requestContext.authorizer. That is the channel for sending the user ID or role downstream.
  5. Caching: responses get cached on the token value, so repeat requests within AuthorizerResultTtlInSeconds never touch the Lambda — fewer invocations and lower latency.

Variants

HTTP API (v2) Authorizer

# HTTP API events have a slightly different shape
def lambda_handler(event, context):
    # headers arrive lowercase in HTTP API
    token = event.get('headers', {}).get('authorization', '').replace('Bearer ', '')

    # event['routeArn'] is still available
    # method lives at event['requestContext']['http']['method']

    claims = validate_jwt(token)
    return {
        'principalId': claims['sub'],
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Allow',
                'Resource': event['routeArn'],
            }],
        },
        'context': {'userId': claims['sub']},
    }

Cognito User Pool Authorizer (No Custom Lambda)

# Wire Cognito straight into the API — no authorizer code at all
Auth:
  DefaultAuthorizer: CognitoAuthorizer
  Authorizers:
    CognitoAuthorizer:
      UserPoolArn: !GetAtt UserPool.Arn
      Identity:
        Header: Authorization

JWT Authorizer for HTTP API (No Lambda Needed)

# HTTP APIs can validate JWTs natively against an external issuer
# (Auth0, Okta, Cognito) — no custom authorizer Lambda required
MyHttpApi:
  Type: AWS::Serverless::HttpApi
  Properties:
    Auth:
      Authorizers:
        OAuth2Authorizer:
          IdentitySource: $request.header.Authorization
          JwtConfiguration:
            issuer: https://YOUR_DOMAIN.auth0.com/
            audience:
              - https://api.example.com
      DefaultAuthorizer: OAuth2Authorizer

Best Practices

  • Enable caching: AuthorizerResultTtlInSeconds between 300 and 900 seconds cuts authorizer invocations by over 90% on repeat requests.
  • Validate token expiry: check the exp claim before accepting — and keep the cache TTL shorter than the token lifetime, or cached policies outlive expired tokens.
  • Use least-privilege IAM policies: scope execute-api:Invoke to the exact route ARN — * has no place here.
  • Pass useful context: put the user ID, role, and permissions in context so handlers don’t re-validate the token.
  • Return Deny, don’t throw: API Gateway turns exceptions into 500s, not 403s. Every validation failure should end in a Deny policy.
  • Use ValidationExpression: with a regex on the Authorization header, malformed tokens get rejected at the gateway — your Lambda never sees them.

Common Mistakes

  • Not caching the authorizer: every request pays a Lambda invocation — 50-200ms of extra latency plus the cost. Always set a TTL.
  • Caching too long: once the TTL outlives the token, revoked credentials stay valid. Stay at or under 300 seconds.
  • Using Deny with a wildcard resource: Deny on * shuts down the entire API. Scope the deny to the requested route ARN.
  • Not handling missing headers: no Authorization header means headers.get('Authorization') returns None — handle that case on purpose.
  • Throwing instead of returning Deny: exceptions surface as 500 errors. Return a Deny policy for every validation failure.

See Also

Frequently Asked Questions

What is the difference between a Lambda authorizer and Cognito authorizer?

The Cognito authorizer validates JWTs issued by Cognito User Pools directly in API Gateway — zero custom code. A Lambda authorizer runs your own code, so it supports any token format: JWTs from other issuers, API keys backed by a database, or OAuth tokens from third-party IdPs.

How does authorizer caching work?

API Gateway caches the returned IAM policy keyed by the token value. For the whole TTL, requests carrying the same token get the cached policy without invoking the Lambda again. A new token — or TTL expiry — triggers a fresh invocation.

How long should the authorizer TTL be?

Keep it shorter than the token's own lifetime. Access tokens that live 15 minutes pair well with a 60–300 second TTL — enough to absorb most repeat calls without letting a revoked token coast on the cache.

Can I use a Lambda authorizer with HTTP API (v2)?

Yes. HTTP APIs support Lambda authorizers with a simpler event shape — lowercase headers and requestContext.http.method instead of httpMethod. A lighter { "isAuthorized": true } response works too if you don't need a full IAM policy.

What is the maximum context size?

Context has a hard ceiling of 10KB. Pass only what the handler actually needs — user ID, role, tenant ID. Everything you put there is also serialized into every cached response.

How do I revoke a cached token?

You can't selectively invalidate a cached authorizer response. Keep the TTL short to shrink the window, and if you need real revocation, check a denylist inside the handler — the authorizer's result may be served from cache.