Keycloak and Apache APISIX API authentication

Protect APIs at the APISIX gateway with Keycloak-issued tokens using the openid-connect plugin, with the flows, mappings and checks that make the setup reviewable.

On this page

How Keycloak and APISIX share the work of API authentication

The gateway checks every request, and Keycloak decides who the caller is. When APIs sit behind an Apache APISIX gateway, APISIX can require a valid Keycloak-issued token before traffic reaches an upstream service. The supported method is the APISIX openid-connect plugin, which the APISIX documentation describes for Keycloak alongside other OpenID Connect providers such as Auth0, Microsoft Entra ID, Google and Okta. In this split, APISIX enforces authentication on the routes you protect, while Keycloak stays the source of identities, client registrations, scopes and token signing keys. Upstream services can then trust the request the gateway forwards without running their own login logic.

The plugin covers four flows, and each one fits a different caller. Authorization code, optionally with PKCE, suits browser users and single-page apps that sign in through the gateway. Client credentials suits service-to-service calls where no human is present. Token introspection lets APISIX ask Keycloak whether an opaque or revoked token is still active, instead of trusting the token signature alone. Decide early which callers use which flow, because each flow needs its own Keycloak client, its own secret handling and its own route configuration. Confirm the exact plugin options for your APISIX version in the plugin documentation before you write them into route definitions.

Plan the trust boundary before you write routes. Confirm which Keycloak client IDs, audiences and scopes the gateway will accept, how the gateway passes user identity to upstream services, and whether upstream services will still check tokens themselves. Keycloak fine-grained authorization, if you use it, sits behind the gateway: APISIX answers whether a valid token reached the route, and the service or Keycloak policy decides what that caller may do. Test a rejected token, an expired token and a token from the wrong client before go-live, because those failure paths show whether the gateway and Keycloak agree.

What you need before connecting APISIX to Keycloak

Most delays in a gateway-to-identity integration come from decisions made before any route is configured. The items below cover the software versions, the gateway deployment, the Keycloak side, the transport security and the network paths that connect the two, along with who owns each one.

Pin the APISIX version

The APISIX downloads page lists 3.19.0, released September 28, 2026, as the current release, and it does not mark any release as long-term support. Pin an exact version in your image or package manifest and record it in your change process, because the openid-connect plugin's options can change between releases. Confirm the plugin's behavior against the version you pin, not against the latest documentation, and schedule the upgrade path as its own work item.

APISIX downloads

Choose the deployment mode

APISIX runs in traditional, decoupled or standalone mode, and the choice sets where configuration lives. Traditional mode listens on port 9080 for client traffic and port 9180 for the Admin API, and decoupled mode shares one etcd cluster between data and control planes. Standalone mode reads conf/apisix.yaml or conf/apisix.json and reloads on change, which suits gitops-managed routes but changes how you roll back and audit gateway settings. Document the mode before writing any plugin configuration.

Deployment modes docs

Create a realm and a client per consumer

Each API consumer, such as a web front end, a batch job or a partner integration, should have its own confidential client in a Keycloak realm, so tokens can be revoked and audited per consumer. Decide which realm holds the API audience and which scopes or roles each client receives before the gateway is configured. Agree who manages realm settings and who approves new clients, since a client created in the wrong realm will fail at the gateway with no obvious error.

Assign ownership for secrets and config

Three teams usually touch this integration: the identity team owns the realm and client secrets, the platform team owns the gateway deployment and etcd or configuration files, and the API team owns routes and plugin settings. Write this split down, including who can rotate a client secret and who can change the openid-connect plugin's settings. Store client secrets in your secrets manager rather than in route files, and confirm that the gateway's Admin API access is limited to the platform team.

Enable HTTPS on both sides

Tokens and client secrets pass between APISIX, Keycloak and the client, so TLS must be in place on the public gateway listener and on the Keycloak hostname that APISIX calls. Confirm that the certificate chain is trusted by the gateway host, because a self-signed or private-CA certificate that is not installed in the gateway's trust store will fail discovery. Keycloak's production guidance also calls for TLS on all communication, so check that requirement against the Keycloak side as well.

Keycloak production guide

Map network paths to Keycloak endpoints

APISIX must reach the Keycloak discovery document, the token endpoint and, for introspection, the introspection endpoint, and it must reach the JWKS endpoint for signature checks. Test each path from the gateway host and from every gateway node, not from a workstation, since firewall rules and egress proxies often differ by subnet. Also confirm that the issuer URL in the discovery document matches the hostname clients use, because a mismatch breaks token validation even when the network path is open.

Configuring the openid-connect plugin against a Keycloak realm

This sequence wires APISIX to a Keycloak realm so that each protected route checks identity before traffic reaches the upstream service. The result is a gateway that redirects browser users to Keycloak, rejects requests without a valid bearer token, and passes verified identity to the backend.

  1. Create the gateway and consumer clients in Keycloak

    A Keycloak administrator creates one confidential client for APISIX in the target realm, with the redirect URI that the gateway will use for the authorization code flow. Each calling application or service gets its own client, so that tokens can be traced and revoked per consumer. Record each client ID and its secret in your secrets manager. The step is done when each client appears in the realm's client list with the expected access type and redirect URIs, and a test sign-in from the admin console returns a token.

  2. Record the issuer and discovery URL

    Open the realm's OpenID Connect discovery document in a browser or with curl and copy the issuer value and the endpoint for the .well-known configuration. APISIX needs the discovery URL to find the authorization, token, introspection and JWKS endpoints, so a mismatch between the issuer and the hostname APISIX calls will cause token validation to fail. Confirm that the hostname in the discovery document is reachable from the APISIX nodes, not only from user browsers. The check is a JSON response that lists the endpoints for your realm.

  3. Add the openid-connect plugin to a route

    An API owner adds the openid-connect plugin to one test route in APISIX, using the discovery URL, the gateway client ID and secret, and the redirect URI from the first step. Start with a single route in a non-production environment, whether you run traditional, decoupled or standalone mode, so that configuration errors stay contained. Store the client secret in a secret reference rather than in plain route configuration where your deployment allows it. The check is that the route saves and the APISIX Admin API accepts the configuration without errors in the gateway log.

  4. Choose the flow each route needs

    Assign a flow to each route based on the caller. Browser-facing routes usually use the authorization code flow with PKCE, so users sign in through Keycloak and APISIX holds the session. Machine-to-machine routes usually use client credentials, and gateways that must check tokens from other clients usually use token introspection. Decide this per route with the application owner and record the decision in your route inventory. The check is a documented flow for each route, which you can verify by sending a request and confirming that the plugin behaves as the flow requires.

  5. Test a request without a token

    Send a request to a bearer-protected route with no Authorization header. For a browser route, expect a redirect to the Keycloak login page with the expected client ID and redirect URI in the query string. For an API route that only accepts bearer tokens, expect an HTTP 401 response from APISIX and no request reaching the upstream service. Check the upstream logs to confirm that the request was not forwarded. If the redirect or the 401 does not appear, review the discovery URL and the route's flow setting before continuing.

  6. Test a request with an expired token

    Obtain a token from Keycloak, wait until its lifetime has passed or use a token issued with a short lifetime set for testing, and send it to the protected route. APISIX should reject the request and the upstream should receive nothing. This step matters because a gateway that validates signatures but ignores expiry will pass stale access to backends. Confirm the token lifetime in the realm token settings before testing so the expiry is predictable. The check is a rejection from APISIX for the expired token, with the reason visible in the gateway error log.

  7. Test a request with a valid token

    Request a token from Keycloak with the consumer client and send it as a bearer token to the protected route. The request should reach the upstream service, and the upstream should receive the identity headers or claims that your route configuration passes through. Verify that the claims match the consumer client and the realm roles or groups you expect. If you use token introspection, also confirm that the gateway reaches the introspection endpoint and that revoking the token in Keycloak causes the next request to fail. The check is a successful response from the upstream with the expected identity context.

Choosing between authorization code, client credentials and introspection

Browser-based applications run on behalf of a signed-in person, so the usual choice is the authorization code flow with PKCE. The user authenticates with Keycloak, the gateway exchanges the returned code for tokens on the server side, and the browser receives a session rather than a bearer token it must protect. In the APISIX openid-connect plugin, this flow relies on the client secret held by the gateway, not by the browser.

  • Secret holder: The confidential client secret stays in the APISIX configuration, and the browser never sees it.
  • Token delivery: The plugin can keep tokens in a session and forward the access token to the upstream service it protects.
  • Local validation: The plugin checks token signatures and claims locally using Keycloak's published keys, then redirects unauthenticated users to sign-in.
  • Keycloak checks: Keycloak handles login, consent and session lifetime, so logout and session policy are configured in Keycloak as well as the gateway.
  • Redirect URIs: Each gateway route that starts a login needs an exact redirect URI registered on the Keycloak client.

Confirm with your application owners whether any single-page app will call the gateway directly, since that changes where tokens are stored.",

How a request flows from client through APISIX to Keycloak and the upstream API

The request starts at the client, which calls a route on Apache APISIX. The openid-connect plugin checks for a valid token, and when none is present it redirects the user to Keycloak's authorization endpoint or returns an error for API clients. Keycloak's discovery and token endpoints sit inside the identity trust boundary, while APISIX and the upstream service sit in the gateway boundary. Check that APISIX validates tokens against Keycloak's published keys or calls introspection, and that only validated requests reach the upstream API.

Token validation happens at the gateway, with Keycloak as the issuer.

Mapping Keycloak claims and clients to APISIX routes and upstream headers

This table maps each Keycloak element (client, scope, audience, role or group claim, token) to the APISIX route rule or forwarded header it drives, and marks what the upstream should receive versus what the gateway should strip. Use it as a design checklist before writing route configuration, then confirm claim names and header options against the openid-connect plugin documentation for your APISIX version.

ElementGateway decisionUpstream receivesConfirm before go-live
Client for the gatewayUse a dedicated confidential client for the APISIX route, separate from the browser or mobile clientNothing directly; the client secret stays on the gatewayClient authentication method and redirect URI match the plugin configuration
Audience (aud) claimRoute only accepts tokens whose audience names the API it protectsAudience value only if the upstream validates it againWhich audience values your Keycloak mappers add to access tokens
Scope claimGate routes or methods on required scopes, such as read or writeScope list if the service applies its own authorizationScope claim name and format in the plugin version you run
Realm or client rolesMap to route-level allow rules, typically per path or HTTP methodRole list in a single header, if the service needs it for local checksClaim path for client roles versus realm roles in your token
Group membershipUse groups only for coarse routing or tenant selection, not as the sole access ruleGroup or tenant identifier needed for data scopingWhether group claims are present in access tokens or only in ID tokens
Subject (sub) and usernameIdentify the caller in logs and rate limitsStable user identifier in a forwarded header, not emailWhich claim you use as the stable identifier in your realm
Raw bearer tokenStrip the Authorization header when the upstream does not need the tokenForward the token only to services that validate it themselvesWhether the plugin can pass the token upstream and under which header name
Introspection or internal tokenUse introspection for opaque or revoked-token checks at the cost of a call to Keycloak per requestKeep the upstream stateless by forwarding verified claims onlyIntrospection endpoint behavior and caching options for your version
Forwarded identity headersSet headers from verified claims only, and remove any client-supplied headers with the same namesTrusted headers set by the gateway, documented as the upstream trust boundaryExact header names and whether the plugin sets them from claims or userinfo

Where Keycloak authorization fits behind the gateway

APISIX can confirm that a request carries a valid Keycloak token, but it does not decide what that caller may do inside a resource. Four placements are common for those decisions, and each moves work, risk and change control to a different team.

Gateway checks token validity only

APISIX verifies the token signature, issuer, audience and expiry through the openid-connect plugin, then forwards the request. The service behind it makes every resource decision. This keeps the gateway simple and fast, but each service must implement its own rules. Confirm which claims the gateway must check, such as audience, and whether it should reject tokens issued for other clients.

openid-connect plugin docs

Keycloak authorization services

Keycloak's fine-grained authorization services let you define resources, scopes and policies in a realm and evaluate them through a permission check. Decisions then live in one place, but the upstream still needs a way to call Keycloak or read the evaluated result. Check whether your policy volume and latency budget suit a central decision point, and who owns policy changes.

Keycloak server admin guide

Decisions inside the upstream service

The upstream application reads roles, groups or claims from the token and applies its own business rules. Developers can express nuanced logic close to the data, and the gateway stays generic. The cost is that rules are scattered across services, so audit and consistent revocation become harder. Confirm which team owns each service's authorization code and how it is tested.

Roles and groups in token claims

Realm roles, client roles and group memberships reach the service as token claims once you add the right client scopes and mappers. The claim names, nesting and size determine what the service can read. A large set of groups can bloat tokens. Confirm the claim format each service expects, which mappers you need, and whether roles should be included only for specific clients.

Token lifetime and revocation

A token that passes gateway checks stays valid until it expires, even if a user loses a role in Keycloak. Shorter access token lifetimes reduce that window but increase refresh traffic. Introspection checks give fresher answers at the cost of a call to Keycloak per request. Decide which permission changes must take effect immediately and test that path.

Questions to settle before choosing

Before choosing a placement, confirm which decisions change often, how many resources and policies exist, the latency each request can absorb, and which team must answer an audit question about who can do what. Also confirm the APISIX and Keycloak versions you will run, because plugin options and client settings differ between releases. Write these answers down before building anything.

Common APISIX and Keycloak failures and how to fix them

This table lists the failures teams most often hit when APISIX validates Keycloak tokens, with the likely cause and the fix for each. Read each row against the symptom you see in the gateway error log or the browser redirect, then check the Keycloak client and the APISIX route configuration in that order. Most failures trace to a hostname, URL or secret that differs between the two systems.

FailureLikely causeFix
Redirect URI mismatchThe redirect URI on the Keycloak client does not exactly match the callback path APISIX uses, often because of a missing path, a trailing slash or an http scheme behind a TLS-terminating proxy.Copy the redirect URI from the APISIX route settings into the Keycloak client, match scheme, host, port and path exactly, and confirm the proxy forwards the original scheme.
Discovery URL unreachable from the gatewayThe discovery URL points at a hostname that resolves only from user browsers, or the APISIX container or pod cannot reach Keycloak over the network path or trust store used for TLS.Test the well-known discovery URL from the APISIX host or pod, add DNS or routing so the gateway can reach Keycloak, and install the internal CA in the gateway trust store.
Issuer mismatch from the proxy hostnameKeycloak builds the issuer from the hostname and proxy headers it receives, so the issuer in the token differs from the issuer APISIX expects when a reverse proxy rewrites the host.Set the Keycloak frontend URL to the public hostname, confirm the issuer in the discovery document, and make the APISIX configuration use that exact issuer value.
Expired tokens after clock skewThe gateway or Keycloak host clock drifts, so a freshly issued token appears not yet valid or already expired when APISIX checks its time claims.Synchronize clocks on Keycloak and every APISIX node with NTP, then review the token lifetime and any allowed leeway the plugin configuration supports.
Introspection endpoint permission errorsThe client used for introspection lacks the access the endpoint needs, or the client is public and cannot authenticate to the token introspection endpoint.Use a confidential client for introspection, confirm the client authentication method in Keycloak, and verify the request with a test call before enabling the route.
Client secret stored in the wrong placeThe client secret is written into the route JSON, a version-controlled file or a plain environment variable, or it is missing from the secret store APISIX reads at startup.Keep the secret in a secret store or Kubernetes secret, reference it from the APISIX configuration as your deployment method documents, rotate it in Keycloak, and never commit it to the repository.
Token accepted but claims missing downstreamThe protected API expects a roles or groups claim that the Keycloak client scope does not include in the access token, so authorization decisions fail after authentication succeeds.Add the needed protocol mapper to the client scope in Keycloak, then decode a sample token to confirm the claim before changing the upstream service.
Unexpected 401 after Keycloak upgradeA Keycloak upgrade changed endpoint behavior, client settings or the signing key set, and the gateway still holds old configuration or cached keys.Review the upgrade notes for the target release, confirm discovery and JWKS values, and retest each route after the change. Plan the upgrade in a non-production environment first.

Testing the integration before it carries production traffic

Run a fixed test set against every protected route before the gateway takes live traffic. The core of the set is token acceptance and rejection: a valid access token issued by Keycloak should pass, and each of these should be refused at APISIX: a token with an invalid signature, an expired token, a token for a different audience, a token from a different realm, and a request with no token at all. Build the wrong-audience case deliberately, because a gateway that checks only the signature will accept a token that Keycloak issued for another client. Confirm the audience and issuer settings in the openid-connect plugin configuration against the claims your Keycloak client actually emits, and record the exact status code and response body APISIX returns for each case.

Repeat the set once for each flow you configured. Authorization code with PKCE should be tested through a real browser sign-in and callback, client credentials through a service account token, and token introspection against a route that depends on it, including what happens when Keycloak cannot be reached during introspection. Test each route separately, because routes often differ in plugins, scopes and upstream services. Then test failure modes: stop one Keycloak node and confirm sign-in and token validation continue through the remaining node, stop one APISIX node and confirm traffic moves to its peer, and confirm the behavior when the Keycloak endpoints are unavailable. Check the APISIX deployment mode documentation for how your chosen mode (traditional, decoupled or standalone) affects which components must stay up.

Treat the results as change evidence. Keep a dated record of the test set version, the Keycloak and APISIX versions, the route list, the client and scope configuration, and the pass or fail result for each case, with the logs or screenshots that support it. Repeat the full set after any upgrade of Keycloak or APISIX, including patch releases, because a change on either side can alter claim formats, token lifetimes or plugin behavior. Confirm current release versions and upgrade notes with the Keycloak upgrading guide and the APISIX release notes before scheduling the retest, not from this page alone.

Questions teams ask before connecting APISIX to Keycloak

What drives the cost of connecting APISIX to Keycloak?

The main drivers are the number of routes that need protection, the number of flows each route uses, how much claim mapping the upstream services need, and how many environments must match production. A single protected route with one client and a standard authorization code flow is a small task. Ten routes with mixed browser, machine-to-machine and introspection traffic, plus scope checks and header forwarding, adds design, configuration and test work at each step. Ask any quote to list routes, flows, claim rules, environments and the test cases that prove each route rejects invalid tokens. Costs recur mainly in upgrades and in changes to routes or clients.

Can our internal team connect APISIX to Keycloak without a partner?

Often yes, if the team already runs both products and has someone who understands OAuth 2.0 and OpenID Connect well enough to reason about token audiences, scopes and redirect URIs. The openid-connect plugin is documented for Keycloak, so the configuration itself is not the hard part. The risk sits in the decisions around it: which clients are confidential, where the client secret is stored, how sessions are kept, and how the gateway and upstream services agree on claims. Teams without that experience usually benefit from an outside review of the design before it reaches production.

What do the Keycloak and gateway owners need to provide?

Keycloak owners need to create or approve the realm, clients, client scopes and protocol mappers, and to confirm the issuer URL, discovery endpoint and token lifetimes. Gateway owners need to supply the route inventory, the upstream services behind each route, the hostnames and TLS certificates, and the Admin API access model for APISIX. Both teams need to agree who owns client secrets, who approves changes to scopes, and where the test environment sits. Without those inputs, most delays come from waiting on decisions rather than from configuration work.

How long does a Keycloak and APISIX authentication project take?

No duration is fixed here, because the answer depends on the factors that drive effort: route count, flows in use, claim mapping complexity, existing Keycloak realm design, and how many environments must be validated. A proof of concept on one route can be scoped quickly, while a multi-route rollout with audit logging and staged promotion takes longer. Ask for a written schedule that ties each milestone to a named route or flow, and confirm which approvals and change windows on both sides could add waiting time.

Which APISIX deployment mode affects the Keycloak setup?

The deployment mode changes how configuration reaches the gateway, not how the openid-connect plugin validates tokens. In traditional mode, APISIX uses etcd and the Admin API on port 9180, while file-driven standalone mode reads conf/apisix.yaml or conf/apisix.json and reloads changes within a second. Teams that manage gateway configuration as code often prefer standalone or GitOps-style delivery, but that choice affects how route and plugin secrets are rotated. Confirm the mode with your platform team before writing the plugin configuration, because it determines where secrets and reload checks live.

Does the openid-connect plugin validate tokens by itself, and what breaks first?

The plugin can verify tokens and redirect unauthenticated browser users, but it does not decide what a user is allowed to do in your services. The common failures are an issuer or discovery URL that does not match the token, audience values that the upstream service does not check, clock skew, and expired refresh handling in browser sessions. Introspection adds a call to Keycloak for each request unless results are cached, so latency and Keycloak load must be tested. Check each failure path with invalid, expired and wrong-audience tokens before go-live.

Do Apache 2.0 licenses cover both Keycloak and APISIX without extra fees?

Keycloak is licensed under Apache 2.0, and Apache APISIX is a top-level Apache Software Foundation project released under the Apache License 2.0 (SPDX: Apache-2.0). Both licenses allow use, modification and redistribution under their terms, and neither requires a license fee to run the software. Confirm the license text and notices that apply to any distribution you ship. Support, hardening, subscriptions and paid editions are separate purchases, so ask a quote to name exactly what is included and what is not.

How DeployOpen scopes and delivers APISIX and Keycloak authentication

DeployOpen plans, implements, hardens, documents and supports self-hosted open-source platforms in the client's own infrastructure, including Keycloak and Apache APISIX. For API authentication, we agree the gateway routes, Keycloak clients, token flows and evidence in writing before the build starts, so your security and platform teams can review every decision.

How we scope

  • Inventory which APIs, routes and consumers move behind the gateway and which flows each one needs.
  • Agree in writing which Keycloak realms, clients, scopes and claims the gateway will rely on.
  • Confirm the APISIX deployment mode, etcd or standalone configuration and the environments in scope before work begins.

How we build

  • Configure the APISIX openid-connect plugin against your Keycloak realm for the agreed authorization code, client credentials and introspection flows.
  • Test token validation, expiry handling, PKCE behavior and denied requests against the routes defined in the scope.
  • Review where Keycloak authorization policies sit behind the gateway and document which checks remain in the upstream services.

How we hand over

  • Deliver the route, plugin and client configuration as versioned files your team can review and reproduce.
  • Document the token flows, claim mappings, secret locations and the test cases used to verify each route.
  • Walk your operations and security staff through runbooks for key rotation, client changes and gateway upgrades.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing for Keycloak and APISIX are available as a retainer.
  • Ask any quote to itemize the scope, the environments covered and the retest and handover work included.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.