Back to Blog
    10 min read

    Use Keycloak Tokens on API Gateway REST APIs Without a Lambda Authorizer

    Hardik Shah
    Hardik ShahCloud Architect & AWS Expert
    Amazon API GatewayKeycloakOIDCJWTAWS LambdaSecurityOAuth 2.0
    Use Keycloak Tokens on API Gateway REST APIs Without a Lambda Authorizer

    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.

    Two panels. Old way: the billing-report app gets a token from Keycloak, calls API Gateway, API Gateway invokes a Lambda authorizer that fetches the Keycloak JWKS, verifies the token and returns an IAM policy before the request reaches the invoices service on Fargate. New way: API Gateway fetches the Keycloak discovery document and JWKS itself, caches them for about 60 minutes, validates the token and scope inline, forwards valid requests with claims to the invoices service and returns 401 or 403 to the client for bad tokens or missing scopes, with no Lambda function.
    Top: a Lambda authorizer sits in the request path. Bottom: API Gateway validates the Keycloak token itself.
    ConcernOld way: Lambda authorizerNew way: JWT authorizer
    Who verifies the tokenYour function, using a JWT library you pick and keep patchedAPI Gateway
    Signing keysYour code fetches the realm JWKS and caches it in memory between invocationsFound through OIDC discovery and cached by API Gateway for about 60 minutes
    Scope checks per methodHand-written in the function, or one policy per scope combinationauthorizationScopes on each method
    ResultAn IAM policy document, cached by token for up to 1 hour if you enable caching401 or 403 at the edge of the API, claims forwarded on success
    LatencyA function invocation on every cache miss, plus cold startsNo invocation in the request path
    CostLambda requests and duration, CloudWatch Logs for the functionNo extra line item beyond API Gateway requests
    Things to ownCode, runtime upgrades, IAM role, invoke permission, logs, alarms, concurrencyOne 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: none and 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.

    ItemValue in this guide
    Keycloak base URLhttps://auth.example.com/identity-service (public HTTPS, Keycloak served under a path)
    Realmplatform
    Issuerhttps://auth.example.com/identity-service/realms/platform
    Audienceinvoices-api
    Scopesinvoices:read, invoices:write
    Read-only clientbilling-report (invoices:read)
    Read and write clientinvoice-sync (both scopes)
    API, authorizer, stageinvoices, invoices-keycloak, v1
    Regionus-east-1

    You need:

    • Keycloak 17 or later (the Quarkus distribution, so issuer URLs have no /auth prefix) reachable from the internet over HTTPS. This guide serves it under /identity-service with KC_HTTP_RELATIVE_PATH=/identity-service and KC_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, curl and jq.

    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.

    StepWhere in the Keycloak admin consoleSettings
    1. Permission scopesClient scopes, Create client scopeName invoices:read, type None, protocol OpenID Connect, Include in token scope on. Repeat for invoices:write.
    2. Audience scopeClient scopes, Create client scope, then its Mappers tabName invoices-audience. Add mapper by configuration, type Audience, Included Custom Audience invoices-api, Add to access token on.
    3. ClientsClients, Create clientbilling-report and invoice-sync: Client authentication on, Service accounts roles on, Standard flow off.
    4. Assign scopesEach client, Client scopes tab, Add client scopeinvoices-audience as Default on both. invoices:read as Optional on both. invoices:write as Optional on invoice-sync only.
    5. Token lifetimeRealm settings, Tokens tabKeep Access Token Lifespan short, 5 minutes is the Keycloak default.
    Client scopes list in the Keycloak admin console for the platform realm, showing invoices-audience, invoices:read and invoices:write as OpenID Connect scopes with assigned type None next to the built-in scopes.
    Steps 1 and 2: the two permission scopes and the audience scope in the platform realm.
    Audience mapper named invoices-api-audience in Keycloak: Included Custom Audience invoices-api, Add to access token on, Add to ID token off.
    The audience mapper inside invoices-audience. Add to access token is the switch that matters.
    Capability config of the billing-report client in Keycloak: Client authentication on, Authorization off, Service accounts roles checked, Standard flow and Direct access grants unchecked.
    Step 3: billing-report as a confidential client that only uses the client credentials grant.
    Client scopes tab of the invoice-sync client in Keycloak filtered to invoices: invoices-audience as Default, invoices:read and invoices:write as Optional.
    Step 4: invoice-sync gets the audience by default and asks for invoices:write when it needs it.

    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:

    bash
    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:

    bash
    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.

    bash
    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:

    Create authorizer form in the API Gateway console with authorizer type JWT selected, identity source header Authorization, allowed algorithm RS256, issuer URL https://auth.example.com/identity-service/realms/platform and audience invoices-api.
    Create authorizer with type JWT. The issuer must match the iss claim exactly.
    API Gateway console card for the invoices-keycloak authorizer: identity source method.request.header.Authorization, algorithm RS256, issuer 1 with the Keycloak issuer URL, audience invoices-api and the JWKS URI that API Gateway resolved from discovery. IDs and URLs are blurred.
    The JWT authorizer after creation. API Gateway shows the key set URI it found through OIDC discovery.

    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.

    bash
    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.

    Edit method request page for POST /invoices in the API Gateway console: authorization invoices-keycloak, authorization scope invoices:write, no request validator, operation name CreateInvoice.
    POST /invoices accepts only tokens that carry invoices:write.

    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.

    bash
    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
    RequestExpected statusWhy
    No Authorization header401Missing token
    Expired token (wait past 5 minutes)401exp passed, beyond the 60 second skew
    Token from another realm401Unknown iss, rejected before any network call
    billing-report, POST403Valid token, no invoices:write
    billing-report, GET200Has invoices:read
    invoice-sync, POST200Has invoices:write
    Terminal output: no token returns Unauthorized with 401, billing-report POST returns Access Denied with 403, billing-report GET returns 200, invoice-sync POST returns 200, and the 403 carries a www-authenticate header naming the missing invoices:write scope.
    The four calls against the v1 stage, plus the header that explains the 403.

    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.

    yaml
    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.azp

    OpenAPI 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 typeHow claims arrive
    Mapping template (non-proxy)$context.authorizer.claims.<name>
    Lambda proxyevent.requestContext.authorizer.claims
    HTTP proxyMap 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.

    bash
    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:

    Authorizers page of the invoices REST API with two cards: invoices-lambda-legacy, a Lambda token authorizer with 300 seconds of caching, and invoices-keycloak, a JWT authorizer with identity source Authorization, RS256, the Keycloak issuer and audience invoices-api. IDs and URLs are blurred.
    A REST API mid migration: the Lambda token authorizer on the left, the JWT authorizer that replaces it on the right.
    • Move each old check into the config: audience checks into audiences, role or group checks into method scopes or additionalClaims rules (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.

    LimitWhat it means with Keycloak
    Issuer must be publicExpose /realms/platform/.well-known/* and /protocol/openid-connect/certs over public HTTPS. The admin console can stay private.
    No revocation checkLogging out or disabling a client does not kill issued tokens. Keep Access Token Lifespan short.
    Keys cached about 60 minutesAfter rotating realm keys, keep the old key active (not removed) for at least an hour.
    AlgorithmsRS256, RS384, RS512, ES256, ES384, ES512. Keycloak's default RS256 works; HMAC and none are rejected.
    kid requiredKeycloak sets it by default. Custom token exchangers must keep it.
    Clock skew60 seconds on exp, nbf and iat. Keep the Keycloak hosts on NTP.
    Issuers and audiences1 to 10 issuers per authorizer, 1 to 100 audiences per issuer. Handy when moving between realms.
    Key endpoint outageCached 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.

    bash
    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"
    SymptomUsual Keycloak cause
    create-authorizer fails on the issuerIssuer 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 tokenThe 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, audienceinvoices-audience is not a Default scope on the client, so aud lacks invoices-api.
    403 with a valid tokenThe client did not request the scope, or the scope is not assigned to it.
    Change has no effectNo 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.

    Hardik Shah

    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.