Sub topic 12
Protecting routes with authorizers
An authorizer is a check that API Gateway runs before it invokes your integration. If the check fails, your Lambda function never runs and you pay nothing for the invocation. This chapter assumes you have deployed an HTTP API with SAM, you know the version 2.0 event shape, and you have a basic grasp of IAM policies and bearer tokens.
The three authorizer types
HTTP APIs support three ways to authorize a route. A route uses at most one of them.
| Type | Who validates | Best for | Caching |
|---|---|---|---|
| JWT | API Gateway, against the issuer's public keys | OpenID Connect or OAuth 2.0 tokens, such as Amazon Cognito | None needed; validation is local |
| Lambda | Your own function | Opaque tokens, API keys, custom rules, database lookups | Optional, 0 to 3600 seconds, 300 by default |
| IAM | AWS, using Signature Version 4 | Callers that already hold AWS credentials | None |
Routes with no authorizer are open to anyone who knows the URL. Decide deliberately which routes stay open, such as a health check.
JWT authorizers
A JWT authorizer needs two settings: an issuer URL and a list of allowed audiences. For Amazon Cognito, the issuer looks like https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE, and the audience is the app client ID.
For each request, API Gateway does the following:
- It reads the token from the identity source, which is
$request.header.Authorizationby default. ABearerprefix is accepted. - It fetches the signing keys from the issuer's
/.well-known/jwks.jsonand verifies the signature. - It checks
iss,aud(orclient_idfor Cognito access tokens),exp,nbfandiat. - If the route lists authorization scopes, it requires the token's
scopeorscpclaim to contain at least one of them.
A missing or invalid token produces 401. A valid token without a required scope produces 403.
Your handler receives the verified claims in the event. Claim values arrive as strings.
def handler(event, context):
jwt = event["requestContext"].get("authorizer", {}).get("jwt", {})
claims = jwt.get("claims", {})
scopes = jwt.get("scopes") or []
user_id = claims.get("sub")
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": f'{{"user": "{user_id}", "scopes": {len(scopes)}}}',
}Trust these claims only because API Gateway already verified the token. Never decode a token yourself from the authorization header and trust it. That bypasses the check.
Lambda authorizers
A Lambda authorizer is a separate function that API Gateway calls before the integration. Use payload format 2.0 for the authorizer, and enable simple responses so the function returns a boolean instead of an IAM policy.
def handler(event, context):
token = event.get("headers", {}).get("authorization", "")
return {
"isAuthorized": token == "Bearer demo-token",
"context": {"user": "demo"},
}The returned context map appears in the backend event at requestContext.authorizer.lambda. Values should be strings, numbers or booleans.
Caching deserves care:
- The cache key is the values of the identity sources you configure, such as the
authorizationheader. Two requests with the same header value share one cached decision. - The decision applies to every route that uses this authorizer. If different routes need different rules for the same token, set the TTL to 0 or let the backend make the finer check.
- A revoked token stays valid until its cache entry expires. Choose a TTL you can accept as the revocation delay.
- If a configured identity source is missing from the request, API Gateway returns 401 without calling your function.
IAM authorization
With IAM authorization, the caller signs the request with Signature Version 4, and API Gateway checks that the caller's identity may invoke the route. The caller's policy must allow execute-api:Invoke on an ARN of this form:
arn:aws:execute-api:us-east-1:123456789012:a1b2c3d4/$default/GET/items/*The parts are the region, account, API ID, stage, HTTP method and path. This suits service-to-service calls and callers with temporary credentials from Cognito identity pools. It does not suit browsers that only hold a user token. The caller identity appears in the event under requestContext.authorizer.iam.
Declaring authorizers in SAM
The template below defines a JWT authorizer as the default for the whole API, adds a Lambda authorizer for one route, and opens a health route.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
Issuer:
Type: String
Audience:
Type: String
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
Auth:
DefaultAuthorizer: JwtAuth
Authorizers:
JwtAuth:
IdentitySource: $request.header.Authorization
JwtConfiguration:
issuer: !Ref Issuer
audience:
- !Ref Audience
TokenAuth:
FunctionArn: !GetAtt AuthorizerFunction.Arn
AuthorizerPayloadFormatVersion: '2.0'
EnableSimpleResponses: true
Identity:
Headers:
- authorization
ReauthorizeEvery: 300
AuthorizerFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: authorizer.handler
CodeUri: src/
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
Auth:
Authorizer: JwtAuth
AuthorizationScopes:
- items:read
Admin:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /admin
Method: GET
Auth:
Authorizer: TokenAuth
Health:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /health
Method: GET
Auth:
Authorizer: NONESAM also grants API Gateway permission to invoke the authorizer function. If you build the authorizer by hand, add a resource-based permission that allows apigateway.amazonaws.com to perform lambda:InvokeFunction. Without it, every request to a protected route fails with a 500-class error.
The handler from earlier chapters returns 404 for /admin and /health because it has no matching branch. Add branches for them before you test those routes.
Testing and diagnosing failures
Call a protected route with and without a token:
API_URL="https://abc123.execute-api.us-east-1.amazonaws.com"
curl -i "$API_URL/items/42"
curl -i "$API_URL/items/42" -H "authorization: Bearer $ACCESS_TOKEN"The first call should return 401. Use this table to read other failures.
| Symptom | Likely cause |
|---|---|
| 401 with a JWT authorizer | Missing header, expired token, wrong issuer, or audience mismatch |
| 403 with a JWT authorizer | Valid token that lacks every scope listed on the route |
| 401 with a Lambda authorizer | Identity source missing from the request |
| 403 with a Lambda authorizer | Authorizer returned `isAuthorized: false`, or a cached denial is still active |
| 500 on a Lambda-authorized route | Authorizer threw an error, returned a malformed response, or lacks invoke permission |
| 403 with IAM | Unsigned request, or the caller's policy does not cover the route ARN |
Turn on access logs and include $context.authorizer.error in the format. It records why the authorizer rejected a request. Your authorizer function's own log group shows its exceptions.
Exercise
A Lambda authorizer with a 300-second cache approved a token at 10:00:00. An administrator revokes that user at 10:01:00, and your authorizer would now deny it. What happens to a request with the same authorization header at 10:02:00, and what are two ways to shorten the exposure?
Show answer
API Gateway still allows the request, because the cache key (the authorization header value) matches the entry cached at 10:00:00, which is valid until 10:05:00. The authorizer function is not called. To shorten the exposure, lower ReauthorizeEvery (down to 0 to disable caching), or keep a short TTL and have the backend also check the revocation list for sensitive routes.