Validating Keycloak access tokens: local JWT checks vs introspection

Compare local JWT signature validation against realm keys with token introspection, and plan audience checks, key rotation and the load each option places on your Keycloak server.

On this page

Choosing how your APIs validate Keycloak access tokens

An API that receives a bearer token from Keycloak has two broad options: validate the token locally by checking its signature against the realm's public keys, or call Keycloak's token introspection endpoint on each request and let Keycloak say whether the token is still active. Local validation is fast and keeps load off Keycloak, but it only proves that Keycloak issued the token and that its claims have not been altered. Introspection adds a live answer about the token's current state, which is the only way an API learns about revocation or a disabled user before the token expires.

The gap that matters is token lifetime. A locally validated JWT remains valid until its exp claim passes, so a session ended in Keycloak, a disabled account or a revoked client can still be accepted by an API for the rest of that window. Shortening access token lifespans in the realm narrows that gap, and the cost is more refresh traffic to Keycloak. Your team should confirm the access token lifespan configured for each client and decide, per API, how much stale access it can tolerate for the sensitive operations it exposes.

Local checks also need every API to verify the audience (aud), issuer (iss) and expected authorized party (azp) on its own. An API that skips the audience check will accept tokens minted for a different client in the same realm. Confirm that each resource server is configured with its own expected audience, and test that a token issued for another client is rejected.

Local JWT checks, introspection and hybrid options compared

This table compares local signature validation, token introspection and a hybrid pattern across the factors that decide how an API verifies Keycloak tokens. Read each row as a trade-off: the option that is cheapest for Keycloak is often the one that accepts revoked tokens for the longest. The main takeaway is that access token lifespan and single logout settings determine how much the revocation gap matters for each API.

FactorLocal JWT validationToken introspectionHybrid (local checks plus selective introspection)
Revocation latencyTokens stay valid until expiry, even after a session ends or a user is disabledRevocation is seen on the next introspection call, subject to Keycloak's answer for inactive tokensRoutine calls are local, while sensitive routes introspect and see revocation there
Load on KeycloakLow, since Keycloak is needed only to fetch and refresh realm signing keysHigh, since every API request or cache miss reaches KeycloakModerate, depending on how many routes introspect and how long results are cached
Dependency on network availabilityAPIs keep verifying tokens if Keycloak is briefly unreachable, once keys are cachedAPIs cannot verify tokens when Keycloak or the network path is downLocal checks continue during outages, but introspected routes fail closed
Issuer checkCompare the iss claim with the exact realm issuer URLSame check, plus the introspection response confirms the token is activeSame check on every request before any local or remote decision
Audience checkValidate aud or azp against the API's expected client or resource identifier, configured with an audience mapperVerify the audience from the introspection response, since it returns claims for the tokenEnforce audience locally on all routes, so a token issued for another client is rejected before any remote call
Expiry and clock checksCheck exp and nbf with a small, documented clock skew allowanceKeycloak reports expiry, but the API still needs its own checks for consistencyLocal expiry checks apply to every request, with introspection as an extra control
Key rotation handlingRefresh the realm JWKS when an unknown kid appears, with a rate limit to avoid repeated fetchesNo key handling needed in the API, since Keycloak judges the tokenKey refresh logic is needed for the local path only
Access token lifespan dependencyShort lifespans bound how long a revoked session can work, so the setting must be chosen with the API's risk in mindLifespan matters less for revocation, but still limits exposure if introspection is cachedShort lifespans for sensitive routes and introspection for the rest reduce the reliance on one setting
Single logout interactionIf logout cannot reach the API, the token remains usable until it expiresIntrospection can reflect an ended session, provided the API does not cache results beyond the acceptable windowLogout reaches sensitive routes through introspection, and other routes rely on the token lifespan
Fit for high-traffic APIsStrong fit when the API tolerates a bounded revocation windowWeak fit at high request rates unless caching is designed and testedCommon fit when most traffic is low risk and a small set of routes needs immediate rejection
Fit for APIs that must reject revoked sessions at onceWeak fit, since revocation waits for expiryStrong fit, subject to the cache window the team acceptsStrong fit for the sensitive routes only, with clear route classification

How local JWT validation uses the realm keys

A resource server validates a Keycloak access token locally by fetching the realm's public signing keys once, then checking the token's signature and claims on every request without calling Keycloak. The starting point is the realm's OpenID Connect discovery document, which points to the JWKS endpoint that publishes the public keys. Confirm the exact discovery and JWKS paths, and the signing algorithms your realm and client settings allow, in the documentation for your Keycloak version before you hard-code anything. Most framework libraries can read the issuer and fetch these values automatically, but your team still needs to know which key set the library trusts.

After the signature verifies, the API must check the claims that a valid signature does not prove. Compare the iss claim with the exact issuer URL of the realm, confirm exp and nbf fall within acceptable clock skew, and check that aud or azp names the client or API your service is meant to accept. Then enforce the scopes or roles the endpoint requires. A token issued to a different client in the same realm can carry a valid signature, so the audience and authorized party checks are the controls that stop it from being accepted. Decide which claims your team treats as mandatory and test rejection for each one.

Keys change. Resource servers usually cache the JWKS for a period and refresh it when they see a token with an unknown kid, but the exact behavior depends on the library. Plan for rotation by confirming that your library refetches keys on an unknown key ID, that it does not accept tokens signed with a retired key after rotation completes, and how long a cache can serve stale keys. Test rotation in a non-production realm before you rely on it. Local validation also means a token stays valid until its expiry, which is why the revocation trade-offs in the next section matter.

How an API checks a Keycloak token on each request

The diagram starts with a client sending a bearer token to the API. The API first checks the token's signature against realm keys it has cached, then checks the audience and expiry. If it needs immediate revocation, it calls Keycloak's introspection endpoint instead, which is the boundary where the API leaves its own trust domain. Check the cache refresh path and the reject response for each branch before you pick a design.

Two validation paths an API can take, with the Keycloak trust boundary marked.

Which claims an API must check beyond the signature

A valid signature only proves that the realm signed the token. The claims inside decide whether this API should accept it, so each check below closes a different way a correctly signed token can still be misused. Run them in the same order on every request, whichever validation method you choose.

Issuer match with realm URL

The iss claim must equal the exact issuer URL of the realm the API trusts, including the realm name. Without this check, a token from another realm on the same Keycloak server, or from a different server that happens to use the same keys, can pass signature checks. Compare the string exactly, and confirm the value your Keycloak sends when the public hostname or reverse proxy changes, since a mismatch there will reject valid tokens.

Keycloak docs

Expiry and clock skew

The exp claim limits how long a stolen or leaked token stays useful, and nbf or iat checks stop tokens from being used before they are valid. Allow only a small, documented clock skew between Keycloak and the API hosts, and keep it tight, because a generous tolerance quietly extends every token's life. Confirm the access token lifespan configured in your realm, since that sets the window this check enforces.

Audience matching the API

The aud claim, or the audience mapper your clients add, must name this API. Without it, a token issued for a web front end or another service can be replayed against your API, because the signature is still genuine. Ask each client team which audience their tokens carry, and reject tokens that list only other resource servers.

Authorized party for multi-client tokens

The azp claim identifies the client that requested the token. When several applications share one realm and one API, check that azp is on the list of clients your API expects. This blocks a token obtained by an unrelated application from being accepted just because its audience and issuer look correct. Keep the allow list in configuration so onboarding a new client is a reviewed change.

Roles and scopes mapping

Roles and scopes sit in claims whose shape depends on client and mapper settings, such as realm roles, client roles and the scope string. Map only the values your API defines to authorities, and deny by default when a required role or scope is missing. Mapping every claim value straight into authorities lets a user gain access through roles that were granted for a different application.

Token type

The typ header and the token's purpose tell an access token apart from an ID token or a refresh token. An API should accept only access tokens meant for it, because an ID token is for the client's own login and should never grant API calls. Reject other token types explicitly, and confirm which token types your client libraries send to each endpoint.

When introspection gives immediate revocation

Token introspection is the option to choose when an API must stop honoring a token soon after the user or session has ended. The API sends the token to Keycloak's introspection endpoint, following the pattern in RFC 7662, and Keycloak answers with an active flag along with claims such as scope, client and expiry. If the user has been disabled, the session has been terminated, or the token has otherwise stopped being valid, Keycloak reports active as false. A local JWT check cannot see that change, because the signature and the exp claim still verify until the token expires. Introspection therefore lets an API see disabled users and ended sessions sooner than a local check can, at the cost of one call to Keycloak.

The cost falls on two places: Keycloak and the request path. Without caching, every API request that carries a token adds a round trip to Keycloak, so the load grows with request volume rather than with token issuance. Most teams add a cache keyed on the token or its hash, and the cache lifetime then sets the revocation delay. A token cached for 60 seconds can remain accepted for up to 60 seconds after Keycloak has deactivated it. Shorter caches shrink that window but raise the call rate. Confirm with your own load tests how much introspection traffic your Keycloak cluster and database can absorb at peak, and set the cache lifetime from the revocation window your security policy allows, not from the default you find in a sample.

Decide per API which risk matters. Read-only endpoints with low impact may accept a short local-check window, while endpoints that change money, permissions or personal data may justify introspection on every call or a very short cache. Also confirm that your API's client has the permissions needed to call the introspection endpoint, and that failures are handled explicitly: if Keycloak is unreachable, the API should fail closed for sensitive operations and document what it does for the rest. Pair this decision with your access token lifespan, because short lifetimes narrow the gap that introspection does not cover.

Handling key rotation without rejected traffic

Most web frameworks and JWT libraries fetch the realm's JSON Web Key Set from the issuer's discovery document and cache the keys in memory. Rotation works when the library refreshes that cache at the right moment, so the key question is how it behaves when a token arrives with a key ID it has not cached yet.

  • Cache refresh: Confirm whether the library refreshes keys on a timer, on a cache miss, or both, and whether either behavior can be configured.
  • Unknown key ID: Check whether the library triggers one immediate JWKS refetch before rejecting the token. Some libraries limit how often they refetch, which can reject valid tokens during a burst of new traffic.
  • Metadata caching: Confirm how the discovery document and JWKS URI are cached, so a changed key endpoint is not missed.
  • Failure mode: Decide whether a failed JWKS fetch keeps serving the last known keys or fails closed, then test the behavior you chose.

During a planned rotation, issue tokens signed with the new key, then confirm that a freshly started instance and a long-running instance both accept them. Check the library's release notes for its refresh behavior before you rely on it.

Setting up token validation in your Keycloak realm

This sequence fixes the issuer, token lifetimes and audience settings in Keycloak first, then lets each API choose local JWT checks or introspection and proves both paths with valid, expired, wrong-audience and revoked tokens.

  1. Confirm the issuer URL and frontend hostname

    The platform team sets the realm's frontend URL so that the issuer (iss) claim in every token matches the hostname your APIs will expect. Keep the admin console and Administration REST API on a different hostname or context path from the public frontend, as Keycloak's production guide recommends, and expose only the paths your reverse proxy needs. Record the issuer value and the JWKS endpoint for the realm. Done when a request to the realm's OpenID configuration document from a machine inside the API network returns the same issuer string that appears in a token you obtain from a test client, and the admin paths do not respond on the public hostname.

  2. Set access token lifespan for each client type

    The security owner sets the access token lifespan in the realm token settings and, where a client needs a different value, in that client's advanced settings. Short access tokens matter most for APIs that validate locally, because a signed JWT stays valid until it expires even if the session is ended in Keycloak. Agree the value with the application and security teams and write it down with the reason. Done when a test token issued to each client shows an exp claim that matches the agreed lifespan, and the decision record names which clients accept revocation delay and why.

  3. Define audience mappers for each API client

    The identity administrator creates an audience mapper on the client that requests tokens for each API, adding the API's client ID or resource identifier to the aud claim. Without this mapper, a token issued for a web front end can be presented to an API that never should accept it. Use one audience value per API so that each resource server can check for its own name. Done when a token issued to the front-end client contains the expected API value in aud, and a token for a different API does not contain it.

  4. Choose the validation method for each API

    The architect decides, API by API, whether the resource server validates the JWT signature against the realm keys or calls the introspection endpoint on each request. Local checks suit high-volume APIs that accept a short revocation delay, while introspection suits APIs where a revoked session must stop access at once, at the cost of a call to Keycloak per request or per cache interval. Write the choice, the expected request volume and the revocation requirement into the API's design notes. Done when every API in scope has a recorded method and an owner who accepted the load and revocation trade-off.

  5. Configure the resource server with JWKS or introspection credentials

    The platform engineer configures each resource server with the realm issuer and either the JWKS URI for local validation or the introspection endpoint plus a confidential client ID and secret for introspection. Confirm the library checks signature, issuer, expiry and audience, and set a key cache interval that refreshes keys when Keycloak rotates them. Store the introspection client secret in your secrets manager rather than in configuration files. Done when the service starts, accepts a valid token, and rejects a token signed by a key that is not published in the realm's JWKS.

  6. Test valid, expired, wrong-audience and revoked tokens

    The QA or security engineer runs four test cases against each API with tokens issued by the realm: a valid token, an expired token, a token whose audience belongs to another API, and a token whose session was ended in Keycloak. Locally validated APIs should accept the revoked token until it expires, and introspecting APIs should reject it promptly. Record the observed result for each case and the time between revocation and rejection. Done when all four results match the recorded design, and any gap is either fixed or accepted in writing by the owner.

Security and operational considerations for token checks

Whichever validation method an API uses, the same small set of mistakes weakens it. The cards below cover algorithm and signature handling, audience scope, introspection credentials, load on Keycloak, transport security and the metrics that show whether token checks are healthy.

Reject unsigned and wrong-algorithm tokens

A local JWT check is only as strong as the algorithm and key it accepts. Pin the expected signing algorithm in the API's validation library, reject tokens that declare none or an algorithm the realm does not use, and load keys only from the realm's certificate endpoint for the issuer you configured. Test this with a deliberately altered token before go-live, because many libraries accept a broad default set of algorithms.

Keycloak docs

Enforce audience checks per API

A token signed by the realm is valid for every client in that realm unless the API checks who it was issued for. Require the aud claim to contain the API's own identifier and reject tokens minted for other APIs, including tokens issued to front-end clients. Confirm in Keycloak that the audience mapper adds the right value to each client's tokens, since missing mappers are a common cause of failed checks.

Store introspection credentials carefully

Introspection requires the API to authenticate to Keycloak as a confidential client. That client secret or signed JWT key grants the ability to ask whether any token is active, so it belongs in a secrets manager or the platform's secret store, not in source control or container images. Scope the client to introspection only, rotate its credential on a schedule, and log who reads it.

Plan for load during traffic spikes

Introspection sends a request to Keycloak for every API call unless results are cached, so a traffic spike turns directly into Keycloak load. Local validation avoids that per-request cost but still needs the realm keys to be cached. Size Keycloak for peak token requests, decide how long a cached introspection result may live, and test both paths under the load you expect rather than assuming either scales.

Encrypt every token exchange

Tokens, introspection requests and client credentials must travel over TLS on every hop, including between the API and Keycloak inside the cluster. Keycloak's production guidance calls for TLS on all communication. Confirm that the issuer URL, JWKS endpoint and introspection endpoint all use HTTPS with certificates the API trusts, and that a reverse proxy in front of Keycloak does not downgrade the connection.

Production guide

Watch token and request metrics

Keycloak exposes Prometheus-format metrics at /metrics on its management interface when started with --metrics-enabled=true. Scrape that endpoint, not the public hostname, and watch token request rates, error rates and response times alongside the API's own validation failures. A rise in rejected tokens or introspection calls usually signals a misconfigured client, an expired key or a spike that needs capacity.

Metrics guide

Questions teams ask before validating Keycloak tokens

How much more effort is local JWT validation than token introspection?

Local validation is usually the smaller build for the API team, because the service fetches the realm's public keys once, caches them and checks the signature, expiry, issuer and audience on each request without calling Keycloak. Introspection is often a shorter code change, since the API sends the token to the introspection endpoint and reads back an active flag, but it adds a network dependency on every call. The real difference in effort sits in the operating model: local checks need key caching, refresh on unknown key IDs and a plan for rotation, while introspection needs capacity planning and a caching policy. Ask your team to price both paths against the number of APIs and languages you run, since each stack has its own JWT and introspection libraries to vet.

What drives the cost of a token validation project?

Cost follows the number of services that verify tokens, the number of languages and frameworks involved, and how much of the existing authorization logic has to change. Other drivers include whether you need immediate revocation for specific APIs, how many realms and clients the APIs must accept, whether audience and scope checks already exist, and how many environments need testing. One-time costs cover design, library selection, changes to each service and test cases for expired, wrong-audience and rotated-key tokens. Recurring costs are the monitoring, upgrade testing and occasional fixes that follow each Keycloak release and each library update. Ask any partner to itemize the services in scope and the test environments they will use before comparing quotes.

What does the validation work need from our internal team?

The work needs owners who can decide the trust model: which APIs accept which clients, what the token lifetime is, and whether revocation must take effect within a fixed window. Your platform or identity team must provide access to the Keycloak realm settings, a test realm that mirrors production clients and the ability to change the configuration of each API. Application teams need to name their audience values, scopes and roles, and they must be available to review code changes and run regression tests. Security should review the signature algorithms accepted, the handling of the none algorithm and any fallback paths. Confirm these owners and their time commitments early, because most delays come from unresolved trust decisions rather than from code.

Can our own team validate Keycloak tokens without a partner?

Yes, many teams do this in-house, especially when they already run Keycloak and maintain a small number of APIs on one framework. The work is manageable when you use a maintained library in each stack, load keys from the realm's published key set, check issuer, audience and expiry explicitly, and write tests for rejected tokens. Teams often need outside help when they must support several frameworks at once, design revocation for high-value endpoints, or prove the controls to an auditor. Check your engineers' familiarity with JWT pitfalls and with Keycloak's signing keys, and make sure someone owns the test suite that will catch regressions after each Keycloak minor release.

How do we test revocation and key rotation before go-live?

Testing should cover three cases: a token that is valid and then revoked or its session ended, a token signed with the previous key after rotation, and a token signed with a key the API has never seen. For local checks, rotate keys in a test realm and confirm the API refreshes its cache and rejects tokens from a key you removed. For introspection, revoke a session and confirm the API stops accepting the token within the caching window you chose. Time for these tests depends on how many services and key rotation paths you have, and on whether your test environment can reproduce production realm settings. Ask a partner to show the test cases and the environment they will run them in.

How would a partner scope a Keycloak token validation engagement?

A partner should start with an inventory of the APIs that verify tokens, the languages and gateways they use, the clients and realms they accept, and the revocation and latency requirements for each. The written scope should name the validation method per service, the libraries to be used, the changes to each codebase, the test cases, the environments and the handover documentation. It should also state what the partner will not do, such as changes to Keycloak client policies or token lifetimes unless those are listed separately. Fixed-scope work of this kind is agreed in writing before work starts, and the quote follows from that scope. Ask for a named list of deliverables and acceptance criteria so you can compare proposals on the same basis.

Limits to confirm in your environment

Token validation looks simple until the details of your Keycloak version, libraries, gateway and compliance rules are fixed. The cards below list the limits to confirm before you pick local JWT checks, introspection, or a mix of both. Each one changes how the API behaves when keys rotate, a session is revoked, or Keycloak is under load.

Exact Keycloak version and defaults

Confirm the Keycloak version you run and read its token and signing defaults for that release, not for an older one. The current release at the time of writing is 26.8.1, and the project ships minor releases several times a year, so defaults can move between upgrades. Record the realm's active signing algorithm, the access token lifespan and whether the realm issues tokens with the audience claim your APIs check. Re-verify these values after every upgrade.

Upgrading guide

Accepted signing algorithms

Each JWT library in your APIs and gateways decides which algorithms it will accept, and some default to permissive settings. Pin the algorithm list to the one your realm signs with and reject none and any algorithm you do not use. Confirm that the library does not trust the algorithm named in the token header over the one configured for the key. Test a token signed with an unexpected algorithm against each service before go-live.

JWKS refresh and key rotation support

Local validation depends on fetching the realm's public keys from the JWKS endpoint and refreshing them when Keycloak rotates keys. Ask whether your gateway or framework caches keys, how long, and whether it refetches on an unknown kid. A cache that never refreshes will reject valid tokens after rotation, and one that refetches on every request adds load to Keycloak. Confirm the behavior with a rotation test in a non-production realm.

Gateway introspection capability

Find out whether your API gateway or service mesh can call the Keycloak introspection endpoint, authenticate its own client, and cache the result. Some gateways validate JWTs natively but cannot introspect, and others add introspection only through custom plugins that you must build, test and patch. Ask who maintains that plugin and how it behaves when Keycloak is slow or unreachable. Decide whether a failed introspection call fails open or closed.

Keycloak high availability architecture

Your Keycloak architecture sets how much introspection traffic it can absorb and what happens during a site failure. Confirm whether you run a single cluster, a multi-cluster design, or the deprecated multi-cluster v1 design, and whether the database replicates synchronously as the supported designs require. Estimate the introspection request rate from your API traffic and test it against the cluster, because every uncached call lands on Keycloak. Ask your team to agree on the cache lifetime that the load test supports.

HA overview

Revocation and token lifetime requirements

Your compliance or security team may set a maximum time between revoking access and the API refusing it. That requirement decides whether short access token lifespans with local checks are enough, or whether each request must introspect. Get the requirement in writing, including how it applies to privileged roles and to sessions that users end in the browser. Document the chosen lifespan and any exceptions, and map them to the controls your auditor will test.

How DeployOpen scopes token validation work

Token validation is scoped per API, not per realm. A written engagement starts with an inventory of every API, gateway, reverse proxy and service that accepts a Keycloak token, including who calls each one, how often, and which data it returns. For each entry, DeployOpen records whether the component can verify a JWT locally against the realm keys, whether it can call the token introspection endpoint, or whether it depends on a gateway plugin that makes the choice for it. That inventory sets the decision for each API, so a high-volume read endpoint and a payment or admin action in the same estate may end up with different validation methods.

The configuration work then covers the Keycloak side as well as the API side. DeployOpen reviews how each client is defined, which audience values the access tokens carry, how the issuer URL is set when Keycloak sits behind a reverse proxy, and how key rotation will reach each verifier. The output is a set of client and audience settings, plus validation rules that match the decision made for each API. Your team should confirm which Keycloak release and realm configuration the estate runs before the review starts, because token claims and endpoint behavior are tied to the version in use.

Testing focuses on negative cases: expired tokens, tokens signed by an old or unknown key, tokens issued for another audience, tokens from a different issuer, revoked sessions when introspection is in use, and requests with malformed or missing bearer headers. DeployOpen delivers the test results, the fixes and a runbook that covers key rotation, introspection endpoint failures and the steps to change a validation method later. Pricing and duration come from the written scope for your environment, and the quote should name which APIs, gateways and Keycloak clients are 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.