
Until November 2026, putting Keycloak in front of an Amazon API Gateway REST API meant writing a Lambda authorizer: fetch the realm's signing keys, verify every token, return an IAM policy. REST APIs now have a native JWT authorizer that does that work inside API Gateway. This guide sets up a Keycloak realm, connects it to a REST API with per-method scopes, tests it with curl and shows how to retire the Lambda.
What changed for REST APIs?
API Gateway REST APIs gained a JWT authorizer type. You list the issuers you trust, the audiences you accept and the signing algorithms you allow. API Gateway finds the signing keys through OIDC discovery, validates each token itself and passes the claims to your backend. Before this, the only built-in token authorizer on REST APIs accepted Cognito tokens.
HTTP APIs have had a JWT authorizer for years, but many teams stay on REST APIs for usage plans, API keys, AWS WAF, request validation, private endpoints or edge-optimized endpoints. Those teams had no native option for Keycloak until now. The new authorizer works on Regional, edge-optimized and private REST APIs.
How does the old way compare with the new way?
In the old way, API Gateway hands every uncached token to a Lambda function you wrote and maintain, which downloads the Keycloak keys, verifies the token and returns an IAM policy. In the new way, API Gateway reads the Keycloak discovery document once, caches the keys and runs the same checks inline. The function, its role and its logs disappear.
| Concern | Old way: Lambda authorizer | New way: JWT authorizer |
|---|---|---|
| Who verifies the token | Your function, using a JWT library you pick and keep patched | API Gateway |
| Signing keys | Your code fetches the realm JWKS and caches it in memory between invocations | Found through OIDC discovery and cached by API Gateway for about 60 minutes |
| Scope checks per method | Hand-written in the function, or one policy per scope combination | authorizationScopes on each method |
| Result | An IAM policy document, cached by token for up to 1 hour if you enable caching | 401 or 403 at the edge of the API, claims forwarded on success |
| Latency | A function invocation on every cache miss, plus cold starts | No invocation in the request path |
| Cost | Lambda requests and duration, CloudWatch Logs for the function | No extra line item beyond API Gateway requests |
| Things to own | Code, runtime upgrades, IAM role, invoke permission, logs, alarms, concurrency | One JSON configuration |
Why does removing the Lambda authorizer matter?
The Lambda authorizer is security code that every API call depends on, and on most teams one person wrote it and nobody tests it. Delete it and the request path loses a deployable unit, a runtime upgrade cycle and a throttling risk. What stays is a JSON file you review in a pull request.
- Nothing to patch: no JWT library CVEs, no Node.js or Python runtime deprecation emails, no redeploy to bump a dependency.
- No cold starts or throttles. A traffic burst can't use up the function's concurrency and turn into 500 errors on every API that shares it.
- Each environment needs one less function, execution role, invoke permission, log group and error alarm.
- API Gateway rejects
alg: noneand HMAC tokens and checks issuer, audience, expiry and not-before itself. A check someone forgot in hand-written code can't leave the API open. - Read and write permissions sit next to the route they protect, where a reviewer sees them in CloudFormation or OpenAPI.
Keep a Lambda authorizer when you need logic a token check cannot express: token introspection, lookups in a database, credentials that are not JWTs, or decisions based on the request body.
What will you build?
You will build an invoices REST API in us-east-1 protected by a Keycloak realm called platform. GET /invoices needs the invoices:read scope and POST /invoices needs invoices:write. Two machine clients use the OAuth 2.0 client credentials flow, each with different scopes.
| Item | Value in this guide |
|---|---|
| Keycloak base URL | https://auth.example.com/identity-service (public HTTPS, Keycloak served under a path) |
| Realm | platform |
| Issuer | https://auth.example.com/identity-service/realms/platform |
| Audience | invoices-api |
| Scopes | invoices:read, invoices:write |
| Read-only client | billing-report (invoices:read) |
| Read and write client | invoice-sync (both scopes) |
| API, authorizer, stage | invoices, invoices-keycloak, v1 |
| Region | us-east-1 |
You need:
- Keycloak 17 or later (the Quarkus distribution, so issuer URLs have no
/authprefix) reachable from the internet over HTTPS. This guide serves it under/identity-servicewithKC_HTTP_RELATIVE_PATH=/identity-serviceandKC_HOSTNAME=https://auth.example.com/identity-service; drop the path if yours runs at the root. - An IAM principal that can manage API Gateway, the latest AWS CLI v2,
curlandjq.
How do you set up the Keycloak realm?
Create two client scopes that carry the permission names, one more client scope that adds the API audience, and two confidential clients with service accounts enabled. Keycloak signs access tokens with RS256 and puts a kid in the header by default, which is what the API Gateway authorizer expects.
| Step | Where in the Keycloak admin console | Settings |
|---|---|---|
| 1. Permission scopes | Client scopes, Create client scope | Name invoices:read, type None, protocol OpenID Connect, Include in token scope on. Repeat for invoices:write. |
| 2. Audience scope | Client scopes, Create client scope, then its Mappers tab | Name invoices-audience. Add mapper by configuration, type Audience, Included Custom Audience invoices-api, Add to access token on. |
| 3. Clients | Clients, Create client | billing-report and invoice-sync: Client authentication on, Service accounts roles on, Standard flow off. |
| 4. Assign scopes | Each client, Client scopes tab, Add client scope | invoices-audience as Default on both. invoices:read as Optional on both. invoices:write as Optional on invoice-sync only. |
| 5. Token lifetime | Realm settings, Tokens tab | Keep Access Token Lifespan short, 5 minutes is the Keycloak default. |




Keycloak already publishes the discovery document API Gateway needs. Check it and copy the exact issuer, because it has to match the iss claim character for character:
KC=https://auth.example.com/identity-service
REALM=platform
ISSUER="$KC/realms/$REALM"
TOKEN_URL="$ISSUER/protocol/openid-connect/token"
curl -s "$ISSUER/.well-known/openid-configuration" | jq '{issuer, jwks_uri}'
# {
# "issuer": "https://auth.example.com/identity-service/realms/platform",
# "jwks_uri": "https://auth.example.com/identity-service/realms/platform/protocol/openid-connect/certs"
# }Request a token for billing-report and decode its payload to confirm the audience and scope landed. Load client secrets from AWS Secrets Manager or your own secret store, not from shell history:
get_token () {
curl -sS -X POST "$TOKEN_URL" \
-u "$1:$2" \
--data-urlencode grant_type=client_credentials \
--data-urlencode "scope=$3" | jq -r .access_token
}
READER_TOKEN=$(get_token billing-report "$READER_SECRET" invoices:read)
cut -d. -f2 <<< "$READER_TOKEN" | tr '_-' '/+' | base64 -d 2>/dev/null \
| jq '{iss, aud, azp, scope, exp}'
# {
# "iss": "https://auth.example.com/identity-service/realms/platform",
# "aud": ["invoices-api", "account"],
# "azp": "billing-report",
# "scope": "invoices:read profile email",
# "exp": 1795859400
# }Keycloak sends aud as an array and adds account by default. That is fine: API Gateway accepts the token when any value matches a configured audience. If aud is missing or says account only, the audience scope is not attached as Default. If scope lacks invoices:read, the scope is not assigned to the client or Include in token scope is off.
How do you create the JWT authorizer?
Create the REST API, write the authorizer configuration to a file and call create-authorizer with --type JWT. The configuration names the Keycloak issuer, the invoices-api audience and RS256. API Gateway reads the discovery document at creation time and fails the call if the issuer in it does not match.
REGION=us-east-1
API_ID=$(aws apigateway create-rest-api --name invoices \
--region "$REGION" --query id --output text)
cat > jwt-config.json <<EOF
{
"issuers": [
{
"issuer": "$ISSUER",
"audiences": ["invoices-api"]
}
],
"defaultAlgorithms": ["RS256"]
}
EOF
AUTHORIZER_ID=$(aws apigateway create-authorizer \
--rest-api-id "$API_ID" \
--name invoices-keycloak \
--type JWT \
--identity-source method.request.header.Authorization \
--jwt-configuration file://jwt-config.json \
--region "$REGION" --query id --output text)Keep jwt-config.json in version control. An update replaces the whole configuration, so every later change sends the full file back.
In the console the same settings live under Authorizers, Create authorizer, with JWT as the type:


How do you require a scope on each method?
Attach the authorizer to each method with --authorization-type JWT and list the scopes that method accepts. A token passes when its scope claim contains at least one of them. The walkthrough uses a mock integration that returns an empty 200; point it at your real invoices service afterwards.
ROOT_ID=$(aws apigateway get-resources --rest-api-id "$API_ID" \
--region "$REGION" --query 'items[?path==`/`].id' --output text)
RESOURCE_ID=$(aws apigateway create-resource --rest-api-id "$API_ID" \
--parent-id "$ROOT_ID" --path-part invoices \
--region "$REGION" --query id --output text)
add_method () {
aws apigateway put-method --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
--http-method "$1" --authorization-type JWT \
--authorizer-id "$AUTHORIZER_ID" --authorization-scopes "$2" \
--region "$REGION"
aws apigateway put-integration --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
--http-method "$1" --type MOCK \
--request-templates '{"application/json":"{\"statusCode\": 200}"}' \
--region "$REGION"
aws apigateway put-method-response --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
--http-method "$1" --status-code 200 --region "$REGION"
aws apigateway put-integration-response --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
--http-method "$1" --status-code 200 --region "$REGION"
}
add_method GET invoices:read
add_method POST invoices:write
aws apigateway create-deployment --rest-api-id "$API_ID" \
--stage-name v1 --region "$REGION"
API_URL="https://$API_ID.execute-api.$REGION.amazonaws.com/v1/invoices"Authorizer and method changes only take effect in a new deployment, so run create-deployment after every change.

How do you test it?
Test the failures first, because a misconfigured authorizer that lets everything through looks identical to a working one on the happy path. A call without a token must return 401, and the read-only client must get 403 on POST. Then confirm both clients get 200 where their scopes allow it.
WRITER_TOKEN=$(get_token invoice-sync "$WRITER_SECRET" "invoices:read invoices:write")
# No token
curl -s -w " %{http_code}\n" "$API_URL"
# {"message":"Unauthorized"} 401
# billing-report has only invoices:read, so POST is refused
curl -s -w " %{http_code}\n" -X POST \
-H "Authorization: Bearer $READER_TOKEN" "$API_URL"
# {"Message":"Access Denied"} 403
# billing-report reads
curl -s -o /dev/null -w "%{http_code}\n" \
-H "Authorization: Bearer $READER_TOKEN" "$API_URL"
# 200
# invoice-sync writes
curl -s -o /dev/null -w "%{http_code}\n" -X POST \
-H "Authorization: Bearer $WRITER_TOKEN" "$API_URL"
# 200| Request | Expected status | Why |
|---|---|---|
No Authorization header | 401 | Missing token |
| Expired token (wait past 5 minutes) | 401 | exp passed, beyond the 60 second skew |
| Token from another realm | 401 | Unknown iss, rejected before any network call |
billing-report, POST | 403 | Valid token, no invoices:write |
billing-report, GET | 200 | Has invoices:read |
invoice-sync, POST | 200 | Has invoices:write |

How do you define it in CloudFormation?
AWS::ApiGateway::Authorizer takes a JwtConfiguration property that mirrors the JSON file, and each AWS::ApiGateway::Method sets AuthorizationType: JWT with its AuthorizationScopes. Pass the Keycloak issuer as a parameter and the same template deploys against your dev, staging and production realms unchanged.
Parameters:
KeycloakIssuer:
Type: String
Default: https://auth.example.com/identity-service/realms/platform
Resources:
InvoicesAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
RestApiId: !Ref InvoicesApi
Name: invoices-keycloak
Type: JWT
IdentitySource: method.request.header.Authorization
JwtConfiguration:
DefaultAlgorithms: [RS256]
Issuers:
- Issuer: !Ref KeycloakIssuer
Audiences: [invoices-api]
CreateInvoice:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref InvoicesApi
ResourceId: !Ref InvoicesResource
HttpMethod: POST
AuthorizationType: JWT
AuthorizerId: !GetAtt InvoicesAuthorizer.AuthorizerId
AuthorizationScopes: [invoices:write]
Integration:
Type: HTTP_PROXY
IntegrationHttpMethod: POST
Uri: https://invoices.internal.example.com/invoices
RequestParameters:
integration.request.header.x-client-id: context.authorizer.claims.azpOpenAPI definitions use the x-amazon-apigateway-authorizer extension with type: jwt and the same jwtConfiguration block.
How does your backend read the Keycloak claims?
API Gateway forwards every validated claim, keeping its JSON type. Mapping templates read $context.authorizer.claims.azp, Lambda proxy integrations get event.requestContext.authorizer.claims, and HTTP proxy integrations need each claim mapped to a header, because they do not forward claims on their own.
| Integration type | How claims arrive |
|---|---|
| Mapping template (non-proxy) | $context.authorizer.claims.<name> |
| Lambda proxy | event.requestContext.authorizer.claims |
| HTTP proxy | Map each one, e.g. integration.request.header.x-client-id to context.authorizer.claims.azp |
For Keycloak service accounts, azp holds the client ID and sub is the service account user's UUID. Log azp; it reads better in an audit trail.
How do you migrate from an existing Lambda authorizer?
Convert the authorizer in place with one update-authorizer call that changes the type, sets the JWT configuration and clears the Lambda fields. Then switch each method to JWT, add its scopes and redeploy. Test on a non-production stage first, and keep the function until production traffic is clean.
aws apigateway update-authorizer \
--rest-api-id "$API_ID" --authorizer-id "$OLD_AUTHORIZER_ID" \
--patch-operations "$(jq -n --rawfile v jwt-config.json '[
{op:"replace", path:"/type", value:"JWT"},
{op:"replace", path:"/jwtConfiguration", value:$v},
{op:"replace", path:"/authorizerUri"},
{op:"replace", path:"/authorizerCredentials"}
]')" \
--region "$REGION"
aws apigateway update-method --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
--http-method GET \
--patch-operations op=replace,path=/authorizationType,value=JWT \
op=add,path=/authorizationScopes,value=invoices:read \
--region "$REGION"
aws apigateway create-deployment --rest-api-id "$API_ID" \
--stage-name v1 --region "$REGION"If you would rather not convert in place, create a second authorizer of type JWT next to the Lambda one and move methods across one at a time. Both can live on the same API while you migrate:

- Move each old check into the config: audience checks into
audiences, role or group checks into method scopes oradditionalClaimsrules (up to 10 per issuer, exact match). - Watch the context keys. A Lambda authorizer exposed whatever you put in its
context; the JWT authorizer exposes raw claims, so update mapping templates and backends that read the old keys. - Delete the function, its role, its invoke permission and its log group last, once its Invocations metric has sat at zero for a few days.
What limits should you know about?
The authorizer trusts up to 10 issuers, reads the token from one header, caches keys for about 60 minutes and never checks revocation. The one that matters most for Keycloak is reachability: API Gateway must fetch the discovery document from the internet, so a realm that only lives inside your VPC will not work.
| Limit | What it means with Keycloak |
|---|---|
| Issuer must be public | Expose /realms/platform/.well-known/* and /protocol/openid-connect/certs over public HTTPS. The admin console can stay private. |
| No revocation check | Logging out or disabling a client does not kill issued tokens. Keep Access Token Lifespan short. |
| Keys cached about 60 minutes | After rotating realm keys, keep the old key active (not removed) for at least an hour. |
| Algorithms | RS256, RS384, RS512, ES256, ES384, ES512. Keycloak's default RS256 works; HMAC and none are rejected. |
kid required | Keycloak sets it by default. Custom token exchangers must keep it. |
| Clock skew | 60 seconds on exp, nbf and iat. Keep the Keycloak hosts on NTP. |
| Issuers and audiences | 1 to 10 issuers per authorizer, 1 to 100 audiences per issuer. Handy when moving between realms. |
| Key endpoint outage | Cached keys keep working for up to an hour; with no cached keys API Gateway returns 5xx, never lets the request through. |
How do you troubleshoot a 401 or 403?
Read the WWW-Authenticate response header first. API Gateway follows RFC 6750 there and names the check that failed, or lists the scopes the method accepts on a 403. Turn on execution logging for the stage to see a claims summary per request, without the raw token.
curl -s -D - -o /dev/null -X POST \
-H "Authorization: Bearer $READER_TOKEN" "$API_URL" | grep -i www-authenticate
# www-authenticate: Bearer scope="invoices:write" error="insufficient_scope"
# error_description="expected scopes within the token"| Symptom | Usual Keycloak cause |
|---|---|
create-authorizer fails on the issuer | Issuer has a trailing slash, drops the path Keycloak is served under (here /identity-service), uses the old /auth/realms/... path, or Keycloak's hostname setting returns a different URL in discovery. |
| 401 for every token | The token's iss uses an internal hostname because the client called Keycloak through a private URL. Set the Keycloak hostname option so tokens always carry the public URL. |
| 401, audience | invoices-audience is not a Default scope on the client, so aud lacks invoices-api. |
| 403 with a valid token | The client did not request the scope, or the scope is not assigned to it. |
| Change has no effect | No new deployment after updating the authorizer or method. |
Data trace logging masks the Authorization header but not custom headers. If you move the identity source to a header like X-Token, leave data trace off on that stage.

About Hardik Shah
Hardik runs Keycloak as the identity provider on the AWS platforms he builds and has maintained the Lambda authorizers this feature replaces, so this guide focuses on what you can delete.