How to configure API Gateway + Cognito + Lambda: a serverless API secured with JWT
Build a secure serverless API end to end: a Cognito user pool and app clients, an HTTP API with a JWT authorizer, and a Lambda on payload 2.0 that reads claims and enforces scopes and groups, all in Terraform and tested with curl.
Cloud$ aws apigatewayv2 get-authorizers --api-id a1b2c3d4e5▍An “open” serverless API ships in ten minutes. The hard part is closing it the right way: only valid tokens get in, each route requires the correct scope, and the function can still make decisions based on who is calling. In this guide we wire the three pieces together, Cognito, HTTP API, and Lambda, with complete Terraform, a Python handler tested locally, and real calls with curl and a Bearer token.
If you don’t know the services on their own yet, first read how to configure AWS Cognito and how to configure API Gateway. Here the focus is the seams between them.
What we will build
client ──(1) gets token──> Cognito (/oauth2/token or InitiateAuth)
│
└──(2) Authorization: Bearer <access token>──> HTTP API
JWT authorizer: signature, iss, client_id, exp, scopes
│ 401 / 403 on failure
▼
Lambda (proxy, payload 2.0)
reads requestContext.authorizer.jwt.claims, checks group
Two routes show the two authorization styles:
GET /ordersrequires the custom scopeorders/read. It is the route for machine-to-machine (M2M) integrations.DELETE /orders/{id}requires a user access token, and the Lambda itself checks that the user belongs to theadminsgroup.
The JWT authorizer and the client_id nuance
The HTTP API JWT authorizer validates the token before invoking the Lambda. In order: it reads the header (a Bearer prefix is allowed), verifies the signature against the keys at the issuer’s jwks_uri (RSA algorithms only), validates kid, iss, aud or client_id, exp, nbf, and iat, and finally requires the token to carry at least one of the route’s authorization_scopes.
Two values configure it all:
- Issuer:
https://cognito-idp.<region>.amazonaws.com/<userPoolId>. - Audience: the list of accepted app client IDs.
And here is the catch. Cognito tokens don’t carry the same claims:
| Claim | ID token | Access token |
|---|---|---|
aud |
app client ID | absent |
client_id |
absent | app client ID |
token_use |
id |
access |
scope |
absent | granted scopes |
cognito:groups |
yes | yes |
Because the access token has no aud, API Gateway checks the audience against client_id. It works, but it has a side effect: without a required scope on the route, an ID token from the same client also gets through. That is why AWS itself recommends always requiring scopes on routes. On the user route we use aws.cognito.signin.user.admin, the scope that access tokens issued by the Cognito API (InitiateAuth) carry, and that ID tokens don’t have.
Complete Terraform
The code creates the user pool, the domain (needed for the /oauth2/token endpoint), a resource server with the orders/read scope, the admins group, two app clients, the Lambda with its role and permission, the HTTP API, the authorizer, the routes, and the stage. It passed terraform validate and terraform fmt -check with the hashicorp/aws provider 6.74.0. We did not run plan or apply: the lab has no AWS account.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "sa-east-1"
}
data "aws_region" "current" {}
# ---------- Cognito ----------
resource "aws_cognito_user_pool" "this" {
name = "your-org-orders"
username_attributes = ["email"]
auto_verified_attributes = ["email"]
}
resource "aws_cognito_user_pool_domain" "this" {
domain = "your-org-orders" # your-org-orders.auth.sa-east-1.amazoncognito.com
user_pool_id = aws_cognito_user_pool.this.id
}
resource "aws_cognito_resource_server" "orders" {
identifier = "orders"
name = "Orders API"
user_pool_id = aws_cognito_user_pool.this.id
scope {
scope_name = "read"
scope_description = "Read orders"
}
}
resource "aws_cognito_user_group" "admins" {
name = "admins"
user_pool_id = aws_cognito_user_pool.this.id
}
# M2M client: client credentials, with a secret and custom scopes only
resource "aws_cognito_user_pool_client" "m2m" {
name = "erp-integration"
user_pool_id = aws_cognito_user_pool.this.id
generate_secret = true
allowed_oauth_flows_user_pool_client = true
allowed_oauth_flows = ["client_credentials"]
allowed_oauth_scopes = aws_cognito_resource_server.orders.scope_identifiers # ["orders/read"]
supported_identity_providers = ["COGNITO"]
}
# TEST client: username and password through the API (never in production)
resource "aws_cognito_user_pool_client" "test" {
name = "test-cli"
user_pool_id = aws_cognito_user_pool.this.id
generate_secret = false
explicit_auth_flows = ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
prevent_user_existence_errors = "ENABLED"
}
# ---------- Lambda ----------
resource "aws_iam_role" "lambda" {
name = "orders-api-lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "lambda.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role_policy_attachment" "logs" {
role = aws_iam_role.lambda.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "aws_cloudwatch_log_group" "lambda" {
name = "/aws/lambda/orders-api"
retention_in_days = 14
}
resource "aws_lambda_function" "orders" {
function_name = "orders-api"
role = aws_iam_role.lambda.arn
runtime = "python3.14"
architectures = ["arm64"]
handler = "app.handler"
filename = "${path.module}/build/app.zip" # zip -j build/app.zip app.py
source_code_hash = filebase64sha256("${path.module}/build/app.zip")
timeout = 10
memory_size = 256
environment {
variables = { ADMIN_GROUP = "admins" }
}
depends_on = [aws_cloudwatch_log_group.lambda]
}
# ---------- HTTP API ----------
resource "aws_apigatewayv2_api" "this" {
name = "orders-api"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_authorizer" "cognito" {
api_id = aws_apigatewayv2_api.this.id
name = "cognito-jwt"
authorizer_type = "JWT"
identity_sources = ["$request.header.Authorization"]
jwt_configuration {
issuer = "https://cognito-idp.${data.aws_region.current.region}.amazonaws.com/${aws_cognito_user_pool.this.id}"
# Cognito access tokens have no "aud": API Gateway checks "client_id" instead
audience = [
aws_cognito_user_pool_client.m2m.id,
aws_cognito_user_pool_client.test.id,
]
}
}
resource "aws_apigatewayv2_integration" "lambda" {
api_id = aws_apigatewayv2_api.this.id
integration_type = "AWS_PROXY"
integration_uri = aws_lambda_function.orders.invoke_arn
payload_format_version = "2.0"
}
resource "aws_apigatewayv2_route" "list" {
api_id = aws_apigatewayv2_api.this.id
route_key = "GET /orders"
target = "integrations/${aws_apigatewayv2_integration.lambda.id}"
authorization_type = "JWT"
authorizer_id = aws_apigatewayv2_authorizer.cognito.id
authorization_scopes = ["orders/read"]
}
resource "aws_apigatewayv2_route" "delete" {
api_id = aws_apigatewayv2_api.this.id
route_key = "DELETE /orders/{id}"
target = "integrations/${aws_apigatewayv2_integration.lambda.id}"
authorization_type = "JWT"
authorizer_id = aws_apigatewayv2_authorizer.cognito.id
authorization_scopes = ["aws.cognito.signin.user.admin"] # blocks ID tokens
}
resource "aws_apigatewayv2_stage" "default" {
api_id = aws_apigatewayv2_api.this.id
name = "$default"
auto_deploy = true
default_route_settings {
throttling_burst_limit = 50
throttling_rate_limit = 100
}
}
resource "aws_lambda_permission" "apigw" {
statement_id = "AllowHttpApiInvoke"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.orders.function_name
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.this.execution_arn}/*/*"
}
output "api_url" {
value = aws_apigatewayv2_stage.default.invoke_url
}
output "token_url" {
value = "https://${aws_cognito_user_pool_domain.this.domain}.auth.${data.aws_region.current.region}.amazoncognito.com/oauth2/token"
}
output "m2m_client_id" {
value = aws_cognito_user_pool_client.m2m.id
}
output "test_client_id" {
value = aws_cognito_user_pool_client.test.id
}
output "m2m_client_secret" {
value = aws_cognito_user_pool_client.m2m.client_secret
sensitive = true
}
Three details that often break the first deploy:
aws_lambda_permission: without it, API Gateway can’t invoke the function and the client gets a 500.payload_format_version = "2.0": it changes the event format. Code written for 1.0 (event["requestContext"]["authorizer"]["claims"]) won’t find the claims.- Log group created before the function: with
depends_on, the 14-day retention applies from the first invocation.
The Lambda: claims at requestContext.authorizer.jwt.claims
In payload 2.0, whatever the authorizer validated arrives at event["requestContext"]["authorizer"]["jwt"], with claims and scopes. Claim values arrive as text, and list claims such as cognito:groups may show up as a string like "[admins readers]". The handler accepts both forms so it doesn’t depend on that detail.
import json
import logging
import os
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
ADMIN_GROUP = os.environ.get("ADMIN_GROUP", "admins")
def _response(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def _as_set(value):
"""List claims may arrive as a list or as a "[a b]" string."""
if not value:
return set()
if isinstance(value, list):
return set(value)
return set(str(value).strip("[]").replace(",", " ").split())
def handler(event, context):
jwt = event.get("requestContext", {}).get("authorizer", {}).get("jwt", {})
claims = jwt.get("claims", {})
scopes = _as_set(claims.get("scope")) | _as_set(jwt.get("scopes"))
groups = _as_set(claims.get("cognito:groups"))
route = event.get("routeKey")
logger.info(json.dumps({"route": route, "sub": claims.get("sub"),
"client_id": claims.get("client_id")}))
if claims.get("token_use") != "access":
return _response(401, {"error": "send an access token"})
if route == "GET /orders":
if "orders/read" not in scopes:
return _response(403, {"error": "missing orders/read scope"})
return _response(200, {"orders": [{"id": 1, "status": "paid"}]})
if route == "DELETE /orders/{id}":
if ADMIN_GROUP not in groups:
return _response(403, {"error": f"only the {ADMIN_GROUP} group"})
order_id = (event.get("pathParameters") or {}).get("id")
return _response(200, {"deleted": order_id})
return _response(404, {"error": "unknown route"})
The scope check inside the Lambda repeats the authorizer’s on purpose: it is defense in depth, in case someone removes authorization_scopes from the route by mistake. The group check, on the other hand, exists only here, because the HTTP API authorizer knows nothing about groups.
Testing locally with a payload 2.0 event
You don’t need an AWS account to test the logic. Build the event dict in the payload 2.0 shape and call the handler:
from app import handler
event = {
"version": "2.0",
"routeKey": "DELETE /orders/{id}",
"rawPath": "/orders/42",
"rawQueryString": "",
"headers": {"authorization": "Bearer eyJ..."},
"pathParameters": {"id": "42"},
"requestContext": {
"http": {"method": "DELETE", "path": "/orders/42", "sourceIp": "203.0.113.10"},
"authorizer": {"jwt": {"claims": {
"sub": "u1", "client_id": "test-client", "token_use": "access",
"scope": "aws.cognito.signin.user.admin",
"cognito:groups": "[admins readers]",
}, "scopes": None}},
},
"isBase64Encoded": False,
}
print(handler(event, None)["statusCode"]) # 200
event["requestContext"]["authorizer"]["jwt"]["claims"]["cognito:groups"] = "[readers]"
print(handler(event, None)["statusCode"]) # 403
In the lab we ran six cases with Python and boto3 1.44.11: GET with and without orders/read, DELETE with and without the admins group, groups as a list and as a string, and a rejected ID token. All returned the expected status. We also simulated the user flow against moto 5.2.6’s mocked Cognito, a local AWS mock: the issued access token had token_use=access, client_id, the aws.cognito.signin.user.admin scope, and no aud, and it passed through the handler with a 200. moto imitates the service, but it doesn’t replace a test in a real account.
Getting a token for testing
Client credentials (M2M) with curl
The M2M client exchanges its ID and secret for an access token at the /oauth2/token endpoint of the pool’s domain. The requested scope must be in allowed_oauth_scopes.
TOKEN_URL=$(terraform output -raw token_url)
M2M_ID=$(terraform output -raw m2m_client_id)
M2M_SECRET=$(terraform output -raw m2m_client_secret)
TOKEN_M2M=$(curl -s -X POST "$TOKEN_URL" \
-u "$M2M_ID:$M2M_SECRET" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&scope=orders/read" | jq -r .access_token)
USER_PASSWORD_AUTH, for test users only
To simulate a user without building a front end, the test-cli client accepts USER_PASSWORD_AUTH: the password goes straight to the Cognito API, with no SRP and no managed login. Use it only in a development pool, with test users and no MFA. In production, users sign in with the authorization code flow and PKCE. Every command and flag below was checked with aws cognito-idp <command> help.
POOL_ID=sa-east-1_EXAMPLE # your pool ID
TEST_ID=$(terraform output -raw test_client_id)
read -rs TEST_PASSWORD # test password, kept out of shell history
aws cognito-idp admin-create-user --user-pool-id "$POOL_ID" \
--username [email protected] --message-action SUPPRESS
aws cognito-idp admin-set-user-password --user-pool-id "$POOL_ID" \
--username [email protected] --password "$TEST_PASSWORD" --permanent
aws cognito-idp admin-add-user-to-group --user-pool-id "$POOL_ID" \
--username [email protected] --group-name admins
TOKEN_USER=$(aws cognito-idp initiate-auth --client-id "$TEST_ID" \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters [email protected],PASSWORD="$TEST_PASSWORD" \
--query 'AuthenticationResult.AccessToken' --output text)
If the password contains a comma, the --auth-parameters shorthand syntax breaks; pass JSON in that case. For more --query and profile tricks, see how to manage AWS with the AWS CLI.
Calling the API with curl
API=https://a1b2c3d4e5.execute-api.sa-east-1.amazonaws.com # terraform output api_url, without the trailing slash
curl -i "$API/orders" # 401: no token
curl -i -H "Authorization: Bearer $TOKEN_M2M" "$API/orders" # 200: has orders/read
curl -i -H "Authorization: Bearer $TOKEN_USER" "$API/orders" # 403: missing orders/read
curl -i -X DELETE -H "Authorization: Bearer $TOKEN_USER" "$API/orders/42" # 200 if in admins
curl -i -X DELETE -H "Authorization: Bearer $TOKEN_M2M" "$API/orders/42" # 403: M2M token lacks the user scope
These calls were not run against AWS; only the logic was tested locally. The expected behavior follows the JWT authorizer documentation.
What about REST APIs?
Until recently, the Cognito path on a REST API was the COGNITO_USER_POOLS authorizer. According to a November 2026 announcement, REST APIs now have native JWT authorizers, with multiple issuers, audiences, allowed algorithms, required claims, and per-method scopes, on Regional, edge-optimized, and private endpoints, with Cognito or any OIDC IdP. The AWS CLI 2.42.1 help already shows --type JWT in aws apigateway create-authorizer.
It is a new feature, so go carefully: the help describes the audience check against the aud claim, which Cognito access tokens don’t have, and Terraform provider 6.74.0 doesn’t expose this block in aws_api_gateway_authorizer yet. Check the current docs before migrating. To choose between REST and HTTP, the table in the API Gateway post still applies.
Troubleshooting: 401 or 403?
| Symptom | Who answered | Likely cause |
|---|---|---|
401 Unauthorized, no token |
Authorizer | Authorization header missing or named differently from the identity_source |
| 401 with a token | Authorizer | Wrong issuer (Region or pool), client_id not in the audience, expired token, or invalid signature |
403 Forbidden |
Authorizer | Valid token, but none of the route’s authorization_scopes |
| 403 with your function’s JSON body | Lambda | An application rule denied it, such as a missing group |
401 with body send an access token |
Lambda | An ID token reached a route with no required scope |
500 Internal Server Error |
API Gateway | Missing aws_lambda_permission, or the function returned an invalid response |
404 Not Found |
API Gateway | The method or path matches no route_key |
To tell them apart quickly, look at the body: authorizer responses come as {"message":...}, your Lambda’s as the JSON you defined. The www-authenticate header on a 401 usually carries the reason. In access logs, include $context.authorizer.error. And decode the token (the middle part is base64url) to check iss, client_id, scope, and exp.
Costs
There is no fixed price: each piece bills on a different dimension. HTTP APIs bill per million requests. Lambda bills per request and per duration in GB-seconds, which depend on memory and architecture. Cognito bills per monthly active user and, for M2M, per token request (check the pricing page, which varies with the pool’s plan). Cache the M2M token until close to its exp instead of requesting a new one on every call. To track and cut spend, see FinOps on AWS. To tune the function, see the AWS Lambda practical guide.
Checklist
- Issuer with the correct Region and pool ID, and an audience with every accepted app client ID
-
authorization_scopeson every protected route, to block ID tokens -
AWS_PROXYintegration withpayload_format_version = "2.0"and anaws_lambda_permission - Lambda reading
requestContext.authorizer.jwt.claimsand enforcing a group or scope -
USER_PASSWORD_AUTHonly on the test client and never in production - M2M token cached until close to expiry
- Access logs with
$context.authorizer.errorand retention set
The authorizer handles who you are; the Lambda decides what you can do. Configure both and the API stays closed for the right reason.