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 downloadsChoose 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 docsCreate 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 guideMap 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.
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.
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.
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.
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.
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.
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.
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.",
Service-to-service calls have no user present, so they use the client credentials flow. A calling service authenticates to Keycloak with its own client ID and secret, receives an access token, and presents it to APISIX as a bearer token. The trust decision rests on the service identity, so each caller should have its own Keycloak client rather than a shared one.
- Secret holder: The calling service holds its client secret, typically from a secrets manager, and must rotate it on a schedule you define.
- Token delivery: The caller sends the token in the Authorization header, and APISIX validates it before forwarding the request.
- Local validation: The plugin verifies the signature, issuer, audience and expiry locally, so most requests do not call Keycloak.
- Keycloak checks: Keycloak issues the token and controls its lifetime, so shorten token lifetimes for services that cannot be interrupted safely.
- Scope mapping: Use scopes or client roles in the token and check them at the gateway or upstream, so each service only reaches the routes it needs.
Confirm how your team will revoke a compromised service client quickly, because local validation will accept a valid token until it expires.",
Token introspection suits cases where a locally checked token is not enough: opaque tokens, tokens that must be revoked before expiry, or stricter per-request checks. The gateway sends the token to Keycloak's introspection endpoint and acts on the active flag in the response. Each request then depends on Keycloak's answer, which affects latency, load and availability planning.
- Secret holder: APISIX needs its own client credentials to call the introspection endpoint, separate from any end user secret.
- Token delivery: After a successful introspection, the plugin forwards the request and can pass selected claims upstream.
- Local validation: Little is validated locally, because the decision comes from Keycloak's response for each token.
- Keycloak checks: Keycloak reports whether a token is active, so revoked sessions are rejected without waiting for expiry.
- Caching and load: Ask the plugin owner to confirm caching options and test the effect on Keycloak under peak traffic before choosing this flow.
Decide which routes truly need revocation checks, because applying introspection everywhere makes Keycloak a hard dependency for all traffic.
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.
| Element | Gateway decision | Upstream receives | Confirm before go-live |
|---|---|---|---|
| Client for the gateway | Use a dedicated confidential client for the APISIX route, separate from the browser or mobile client | Nothing directly; the client secret stays on the gateway | Client authentication method and redirect URI match the plugin configuration |
| Audience (aud) claim | Route only accepts tokens whose audience names the API it protects | Audience value only if the upstream validates it again | Which audience values your Keycloak mappers add to access tokens |
| Scope claim | Gate routes or methods on required scopes, such as read or write | Scope list if the service applies its own authorization | Scope claim name and format in the plugin version you run |
| Realm or client roles | Map to route-level allow rules, typically per path or HTTP method | Role list in a single header, if the service needs it for local checks | Claim path for client roles versus realm roles in your token |
| Group membership | Use groups only for coarse routing or tenant selection, not as the sole access rule | Group or tenant identifier needed for data scoping | Whether group claims are present in access tokens or only in ID tokens |
| Subject (sub) and username | Identify the caller in logs and rate limits | Stable user identifier in a forwarded header, not email | Which claim you use as the stable identifier in your realm |
| Raw bearer token | Strip the Authorization header when the upstream does not need the token | Forward the token only to services that validate it themselves | Whether the plugin can pass the token upstream and under which header name |
| Introspection or internal token | Use introspection for opaque or revoked-token checks at the cost of a call to Keycloak per request | Keep the upstream stateless by forwarding verified claims only | Introspection endpoint behavior and caching options for your version |
| Forwarded identity headers | Set headers from verified claims only, and remove any client-supplied headers with the same names | Trusted headers set by the gateway, documented as the upstream trust boundary | Exact header names and whether the plugin sets them from claims or userinfo |
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.
| Failure | Likely cause | Fix |
|---|---|---|
| Redirect URI mismatch | The 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 gateway | The 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 hostname | Keycloak 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 skew | The 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 errors | The 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 place | The 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 downstream | The 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 upgrade | A 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.

