Sub topic 12
Protecting routes with authorizers
This chapter assumes you can deploy an HTTP API with SAM and that you know the version 2.0 event format from earlier chapters. An authorizer is a check that API Gateway runs before it invokes your integration. If the check fails, the request never reaches your function.
The three authorizer types
HTTP APIs support three ways to protect a route.
| Type | How it decides | Best for |
|---|---|---|
| JWT | API Gateway validates a JSON Web Token against an OIDC issuer | Tokens from Cognito, Auth0 or another OIDC provider |
| Lambda | Your function inspects the request and returns allow or deny | Custom tokens, API keys, database lookups |
| IAM | API Gateway checks a SigV4 signature against IAM policies | AWS-to-AWS calls and callers with IAM credentials |
A JWT authorizer needs no code. API Gateway fetches the issuer's public keys, checks the signature, expiry, iss and aud (or client_id), and optionally the required scopes. A failed check returns 401, or 403 when a scope is missing.
A Lambda authorizer
A Lambda authorizer is a separate function. With the simple response format, it returns a boolean and an optional context map.
def handler(event, context):
token = event.get("headers", {}).get("authorization", "")
return {
"isAuthorized": token == "Bearer demo-token",
"context": {"user": "demo"},
}This assumes simple responses are enabled on the authorizer. The hard-coded token only shows the response shape. In real code, validate a signed token or look the credential up in a store.
Header names in the version 2.0 event are lowercase, so read authorization, not Authorization.
Reading identity in your handler
API Gateway passes authorizer results to your function in the request context. For a JWT authorizer, the claims are under event["requestContext"]["authorizer"]["jwt"]["claims"]. For a Lambda authorizer with simple responses, your context map appears under event["requestContext"]["authorizer"]["lambda"].
def current_user(event):
auth = event["requestContext"].get("authorizer", {})
if "jwt" in auth:
return auth["jwt"]["claims"]["sub"]
return auth.get("lambda", {}).get("user")Trust these values. They come from API Gateway, not from the client. Do not trust a user header or body field sent by the caller.
Attaching an authorizer in SAM
Define the authorizer on the API, then set Auth on each route. A route with no Authorizer is public unless you set a DefaultAuthorizer.
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
Auth:
Authorizers:
JwtAuth:
IdentitySource: $request.header.Authorization
JwtConfiguration:
issuer: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE
audience:
- example-client-id
DefaultAuthorizer: JwtAuthReplace the issuer and audience with your own values.
Common errors
- 401 on every call: the token is missing from the identity source, expired, or has the wrong
issoraud. - 403 with a valid token: the route requires scopes the token lacks, or an IAM caller lacks
execute-api:Invoke. - Preflight requests fail: browsers send
OPTIONSwithout credentials. Configure CORS on the API so API Gateway answers preflight itself. - Stale decisions: Lambda authorizer results are cached by identity source. Set the cache TTL deliberately, since a revoked token may still pass until it expires.
Exercise
A route behind a JWT authorizer returns 403 even though the token is unexpired and signed by the right issuer. What is the most likely cause, and where would you check?
Show answer
The route probably requires scopes that the token does not contain. Compare the route's authorization scopes with the token's scope or scp claim. A 401 would point to a signature, expiry, issuer or audience problem instead.