Token Introspection in Keycloak

Token Introspection in Keycloak

A complete, beginner-friendly guide to how Keycloak lets one service ask another, in real time, "is this token still good?" — and why that single question underpins modern API security.

Imagine a nightclub with a bouncer at the door. Earlier in the evening, the club manager handed out wristbands to paying guests. Hours later, a guest walks up to a second door deeper inside the club — the VIP lounge — and shows their wristband. The bouncer at that door does not know the guest personally. They cannot simply trust the wristband by looking at it, because wristbands can be cut off, forged, or the guest’s membership could have been cancelled five minutes ago. So the bouncer picks up a phone and calls the manager’s office: “I have wristband number 4471 here — is it still valid?” The manager checks a ledger and replies instantly: “Yes, still valid, expires at midnight, and this guest is allowed in the VIP section.” That phone call is, in essence, exactly what token introspection is in the world of software. Keycloak plays the role of the manager’s office, an access token plays the role of the wristband, and any application that needs to check whether the token is trustworthy plays the role of the bouncer. This tutorial walks through that idea from the ground up — no prior security background assumed — and builds up to how real companies use it, what can go wrong, and how to avoid the traps that catch most engineers the first time they wire this up.

1What Is Token Introspection?

Before touching Keycloak specifically, it helps to understand the general problem that introspection solves.

The basic idea

When a user logs into an application, that application does not usually keep asking the user for a password on every single action. Instead, after the first successful login, the user is handed a small piece of digital proof called an access token. Think of it as a temporary ID card. Every time the user tries to do something — view their profile, place an order, upload a file — the application checks this ID card instead of asking for the password again.

But here is the catch: what if the ID card was stolen? What if the user was banned five minutes ago, but their card has not technically “expired” yet? What if the card is fake? Somebody has to be able to answer the question “is this card still valid right now?” — and that somebody, in the Keycloak world, is the introspection endpoint.

Token introspection is simply the act of taking a token and asking the identity server — Keycloak, in this tutorial — to confirm three things: whether the token is still active, who it belongs to, and what that person or service is allowed to do.

Simple Analogy

Think of a train ticket inspector. A passenger’s ticket might look perfectly fine on the surface, but the inspector’s handheld scanner pings a central server to confirm the ticket has not already been used, has not been refunded, and is valid for this exact train. Token introspection is that scanner ping, happening between two computer systems instead of a human inspector and a paper ticket.

Why not just trust the token itself?

This is the single most common question beginners ask, and it deserves a proper answer, because the answer explains the entire rest of this tutorial. It depends on the type of token being used, which is the subject of the next chapter.

i
Where This Fits

Keycloak is an open-source Identity and Access Management (IAM) server. It handles login screens, user databases, password resets, multi-factor authentication, and — the star of this tutorial — issuing and validating tokens on behalf of every application in an organization.

2Access Tokens: Opaque vs Self-Contained

Introspection only makes full sense once you understand that not all tokens are built the same way.

Keycloak, like most modern identity servers, can issue access tokens in two very different shapes. Understanding the difference is the foundation for understanding why introspection exists at all.

Self-Contained

JWT Access Token

A JSON Web Token (JWT) carries all its own information — who it belongs to, what it allows, and when it expires — packed inside itself and cryptographically signed. Any application holding Keycloak’s public signing key can check it locally without calling Keycloak at all.

Reference / Opaque

Opaque Access Token

An opaque token is just a random-looking string, like a lottery ticket number. It carries no readable information by itself. The only way to know anything about it is to ask the issuing server — Keycloak — what it means.

Here is the twist that surprises many newcomers: even a JWT, which technically can be read locally, is often still introspected in real systems. Why bother calling Keycloak if the information is already inside the token? Because a signature only proves the token was genuinely issued by Keycloak at some point in the past — it says nothing about whether that token has since been revoked, whether the session was logged out, or whether an administrator disabled the user’s account thirty seconds ago. A JWT is like a printed movie ticket with a real hologram: the hologram proves the ticket is genuine, but it cannot tell the usher whether the movie got cancelled after the ticket was printed.

Local Validation (Reading the JWT Directly)

  • Extremely fast — no network call needed
  • Works even if Keycloak is briefly unreachable
  • Scales easily under heavy traffic

Local Validation — Trade-offs

  • Cannot detect immediate revocation or logout
  • Cannot reflect account changes made after the token was issued
  • Requires distributing and rotating public signing keys correctly
!
Common Misconception

Many beginners assume that because a JWT can be decoded and read, it is automatically “validated.” Decoding is not the same as validating. A token can be perfectly decodable and still be expired, revoked, or issued for a completely different application.

3The Introspection Endpoint and RFC 7662

Token introspection is not a Keycloak invention — it is a formally standardized protocol that Keycloak implements.

In 2015, the Internet Engineering Task Force (IETF) published a specification called RFC 7662: OAuth 2.0 Token Introspection. Before this document existed, every identity provider had its own private way of letting applications check a token’s status, which meant developers had to relearn a new mechanism every time they switched vendors. RFC 7662 created a shared, predictable contract: any compliant server exposes a single introspection endpoint that accepts a token and returns a small piece of structured information describing its status.

Keycloak follows this standard closely. Every realm — a realm is Keycloak’s word for an isolated tenant or organization space — automatically exposes its own introspection endpoint as part of its OpenID Connect configuration. Any client registered in that realm, provided it has the right credentials, can call this endpoint.

What the Standard Guarantees

Regardless of which identity server issued the token, an application built to the RFC 7662 standard receives a response containing at minimum a field indicating whether the token is currently active. Optional fields can include the token’s owner, its scopes, its expiry time, and the client it was issued to.

What makes this standardization powerful is that it decouples the resource server — the application actually protecting data, such as an order-processing API — from the authorization server — Keycloak itself. The resource server does not need to understand Keycloak’s internal database structure, its session storage, or its cryptography. It just needs to send the token to one URL and read a simple yes-or-no answer back.

2015
Year RFC 7662 was published
1
Endpoint per Keycloak realm
2
Credentials typically required — client ID and secret

4Keycloak’s Architecture Behind Introspection

To understand what actually answers the introspection call, it helps to see the pieces that make up a Keycloak deployment.

Keycloak is not a single monolithic box that only checks tokens. It is a full identity platform, and introspection is one small — but crucial — feature sitting on top of several larger components working together.

Realm

Isolation Boundary

A realm is a self-contained space with its own users, roles, and clients. A company might run one realm for employees and a separate realm for external customers, and tokens from one realm are meaningless in another.

Client

Registered Application

Every application that wants Keycloak to issue or check tokens must first be registered as a “client” inside a realm, with its own identifier and, usually, a secret credential.

User Session Store

Live Session Memory

Keycloak keeps track of who is currently logged in, which tokens belong to which session, and whether a logout has invalidated them — this is the ledger the bouncer’s phone call reaches.

Introspection Endpoint

The Answer Desk

A dedicated HTTP endpoint, one per realm, that receives a token and a set of client credentials, checks the session store and token metadata, and replies with the result.

When a resource server calls the introspection endpoint, Keycloak does not simply decode the token and hand back its contents blindly. It cross-references the token against its live internal records — checking whether the session is still active, whether the specific token was explicitly revoked, and whether the client asking the question is even allowed to ask about this particular token. This last point matters: Keycloak will not let just any application introspect any token; the caller must present valid credentials for a client that is permitted to use the introspection endpoint.

i
Confidential vs Public Clients

Keycloak distinguishes “confidential” clients, which hold a secret and can safely make server-to-server calls like introspection, from “public” clients such as single-page apps, which cannot keep secrets safe and are therefore not expected to call the introspection endpoint directly.

5How Introspection Works, Step by Step

Now that the pieces are on the table, here is the sequence of events from the moment a request arrives at a protected service.

1

Client sends an access token

A mobile app, browser, or another service sends a request to a protected API, attaching the access token it received earlier from Keycloak, typically in an authorization header.

2

Resource server extracts the token

The API — the “resource server” in OAuth terminology — pulls the token out of the incoming request without yet trusting anything about it.

3

Resource server calls Keycloak’s introspection endpoint

Using its own registered client credentials, the resource server sends the token to Keycloak’s introspection endpoint over a secure, server-to-server connection.

4

Keycloak checks its internal records

Keycloak looks up the token’s session, expiry, and revocation status, and confirms the requesting client is authorized to introspect it.

5

Keycloak responds with structured metadata

The response includes whether the token is active, and if so, details such as the username, granted scopes, client ID, and expiry timestamp.

6

Resource server makes the final decision

Based purely on that response, the resource server decides whether to fulfil the original request, reject it, or apply narrower permissions based on the returned scopes.

Simple Analogy

This is exactly like calling a credit card company’s verification line before completing a large purchase. The merchant does not decide on their own whether the card is good — they dial in, read out the card number, and the bank’s system replies “approved” or “declined,” along with the remaining credit limit. The merchant then acts strictly on that answer.

6The Full Request-Response Lifecycle

Zooming out, here is the entire lifecycle of a token from creation to introspection, shown as a diagram.

sequenceDiagram
    participant U as User
    participant A as Application
    participant K as Keycloak
    participant R as Resource Server
    U->>A: Logs in
    A->>K: Sends login credentials
    K-->>A: Returns access token
    A->>R: Calls protected API with token
    R->>K: POST /introspect with token
    K->>K: Checks session store and revocation list
    K-->>R: Returns active: true/false + metadata
    R-->>A: Allows or denies the request
        
FIG 1 — End-to-end flow from login through introspection to final authorization decision

Two facts about this lifecycle are worth sitting with. First, the token itself never changes shape as it travels from the application to the resource server — it is the exact same string handed over at login. Second, the resource server never talks directly to the user’s original login session; it only ever talks to Keycloak’s introspection endpoint, which acts as the single, authoritative source of truth for whether that session is still alive.

This separation is deliberate and valuable. It means a company can have dozens or hundreds of resource servers — order services, inventory services, notification services — none of which need their own copy of user session data. They all lean on one shared authority.

“The resource server doesn’t need to know who you are — it only needs to know who to ask.”

7Advantages and Trade-offs

Introspection is not free — it trades some performance for a meaningful security guarantee. Here is that trade honestly laid out.

Advantages

  • Immediate revocation — a logout or admin-disabled account is reflected instantly, not after the token happens to expire
  • Works uniformly for opaque tokens, which cannot be read any other way
  • Centralizes trust in one authoritative service instead of scattering signing keys everywhere
  • Simplifies resource servers — they need almost no cryptography knowledge
  • Naturally supports fine-grained, up-to-the-second scope and permission checks

Disadvantages / Trade-offs

  • Adds a network round trip to every protected request, increasing latency
  • Creates a hard dependency — if Keycloak is down or slow, protected APIs are affected too
  • Increases load on the identity server proportional to overall API traffic
  • Requires every resource server to hold and protect its own client credentials

Because of this trade-off, most production systems use a hybrid strategy: they read a signed JWT locally for everyday authorization decisions — which is nearly instantaneous — but still call introspection selectively for particularly sensitive actions, or they cache introspection results for a very short window, such as a few seconds, to reduce load while still catching revocations quickly.

i
A Practical Rule of Thumb

The more damage a wrongly-approved request could cause — transferring money, deleting an account, exporting sensitive data — the stronger the case for paying the extra network cost of introspection rather than relying purely on a locally-decoded token.

8Security Considerations

Introspection strengthens security in some ways, but it introduces its own attack surface that must be defended carefully.

Protecting the introspection endpoint itself

Because the introspection endpoint reveals information about a token — including, in some configurations, the identity of the user behind it — Keycloak requires the calling client to authenticate itself, usually with a client ID and secret, before it will answer. Without this safeguard, any anonymous party could probe arbitrary tokens fishing for valid ones or leaking user information.

Transport security

Every introspection call must travel over an encrypted channel (HTTPS/TLS). An access token sent in plain text across a network is functionally equivalent to a physical key photographed and mailed on a postcard — anyone intercepting the traffic could reuse it.

Token leakage through logging

A surprisingly common real-world mistake is logging the raw token value in application logs “just for debugging.” If those logs are ever exposed — through a misconfigured dashboard, a shared file, or a breached logging system — an attacker gains a live, valid credential without needing to break any cryptography at all.

!
Common Mistake

Treating an access token as harmless because “it’s just a random string” is a serious misjudgment. Until it expires or is revoked, that string is functionally equivalent to the user’s identity — anyone holding it can act as that user against any resource server that trusts it.

Client credential hygiene

Since resource servers need their own client secret to call introspection, that secret becomes a high-value target. Storing it in a secrets manager rather than a configuration file checked into source control is considered essential practice, not an optional extra.

Defense in Depth

Mature deployments layer multiple protections: short token lifetimes, HTTPS everywhere, restricted network access to the introspection endpoint, audit logging of introspection calls, and rate limiting to slow down anyone attempting to guess tokens by brute force.

9Monitoring, Logging, and Metrics

Because introspection sits directly in the request path of protected services, watching its health closely is not optional.

Latency

Introspection Response Time

Since every protected request may now wait on this call, teams typically track average and worst-case (p99) response times, alerting if the endpoint slows down beyond an agreed threshold.

Volume

Requests Per Second

Tracking call volume over time helps capacity planning — a sudden spike may indicate either legitimate traffic growth or a misbehaving client retrying too aggressively.

Outcome Ratio

Active vs Inactive Responses

An unusual jump in “inactive” (invalid/expired) responses can signal expired credentials being reused by a client that has a bug, or an attacker probing with stolen tokens.

Failure Rate

Timeouts and Errors

Failed introspection calls due to network issues or Keycloak overload need immediate visibility, since resource servers depending on them may start rejecting valid users.

Keycloak itself exposes operational metrics and can be integrated with standard observability stacks. Beyond raw numbers, many organizations also keep an audit trail of which clients introspected which tokens and when, both for security investigations and for compliance requirements in regulated industries such as banking and healthcare.

i
A Useful Signal

A sudden, sustained rise in introspection calls returning “inactive” for tokens that should still be valid is often the very first visible sign of a clock synchronization problem between servers, rather than an actual security incident.

10Design Patterns and Anti-Patterns

Over years of production use, certain approaches to introspection have proven themselves, and others have proven costly.

Pattern: Short-lived cache in front of introspection

Rather than calling Keycloak on every single request, many teams cache the introspection result for a very short duration — often just a few seconds — keyed by the token itself. This dramatically reduces load on Keycloak while keeping the delay before a revocation takes effect small enough to be acceptable for most applications.

Pattern: Gateway-level introspection

Instead of every microservice independently calling Keycloak, many architectures place a single API gateway at the network edge that performs introspection once per incoming request, then passes along a lightweight, already-verified identity to internal services. This avoids dozens of services all hammering Keycloak for the same token.

ANTI-PATTERN-01 Avoid
Problem

Every internal microservice, including ones deep inside a private network that never receives external traffic directly, independently calls the introspection endpoint for every request it handles, even requests that were already verified once at the edge gateway.

Why It’s Harmful

This multiplies load on Keycloak needlessly, adds redundant latency at every hop, and creates a fragile system where a slowdown in Keycloak cascades into a slowdown across the entire request chain, service after service.

Correct Approach

Introspect once at the trust boundary — typically the API gateway — then propagate a signed, short-lived internal token or a simple verified-identity header to downstream services, which trust the gateway rather than re-verifying independently.

ANTI-PATTERN-02 Avoid
Problem

A team hardcodes the client secret used for calling introspection directly into application source code or a checked-in configuration file.

Why It’s Harmful

Anyone with read access to the code repository — including former employees, external contractors, or anyone who later gains unauthorized repository access — obtains a credential capable of probing arbitrary tokens.

Correct Approach

Store the client secret in a dedicated secrets manager or environment-injected configuration that is never committed to source control, and rotate it periodically.

11Best Practices and Common Mistakes

A checklist-style summary of what separates a solid introspection setup from a fragile one.

1

Always use HTTPS for the introspection call

Never allow the token or the client secret to travel over an unencrypted connection, even inside a private network, since internal networks can still be compromised.

2

Set realistic token lifetimes

Tokens that never expire defeat much of the purpose of having an expiry field at all; short, sensible lifetimes reduce the window of damage from a leaked token.

3

Use caching thoughtfully, not blindly

A cache improves performance but should be short enough that a revoked token cannot be reused for an uncomfortably long window.

4

Never log raw tokens or secrets

Mask or omit token values entirely in application logs, error messages, and monitoring dashboards.

5

Monitor Keycloak’s own health, not just the application

Since introspection introduces a dependency, treat Keycloak’s uptime and latency as a first-class concern for every protected service, not an afterthought owned solely by the identity team.

!
Frequently Seen Mistake

Assuming introspection alone is “the security layer” and skipping proper authorization logic afterward. A token being active only proves the caller is who they claim to be — the resource server must still separately check whether that identity is allowed to perform the specific action being requested.

12Real-World and Industry Examples

Token introspection is not an academic exercise — it underpins systems people rely on every day.

Banking and Financial Services

Financial institutions often favor introspection heavily, sometimes over locally-verified JWTs, precisely because immediate revocation matters so much. If a customer reports a stolen phone, the bank needs the associated session invalidated within seconds, not whenever a token’s normal expiry happens to arrive.

Healthcare Platforms

Systems handling patient records under regulations such as HIPAA in the United States frequently combine introspection with detailed audit logging, so that every access to sensitive data can be tied back to a verified, still-active session at the exact moment of access.

Enterprise Software-as-a-Service Platforms

Large business software vendors that serve many corporate customers through Keycloak-based realms use introspection at their API gateways to enforce per-customer session policies, such as immediately terminating access when an administrator removes an employee’s account.

Internal Microservice Ecosystems

Companies running large numbers of internal services — order management, billing, shipping, customer support tools — commonly centralize identity in Keycloak and use gateway-level introspection so that dozens of teams never have to build their own authentication logic from scratch.

13Frequently Asked Questions

Q1Does introspection work for both opaque tokens and JWTs?

Yes. It is especially necessary for opaque tokens, which cannot be read any other way, but it is also commonly used with JWTs whenever an application needs to confirm real-time revocation rather than relying solely on the token’s embedded expiry.

Q2Is introspection the same thing as logging in?

No. Logging in is the process of proving identity to obtain a token in the first place, usually through a username and password or another authentication method. Introspection happens afterward, whenever a resource server needs to double-check a token that was already issued.

Q3What happens if Keycloak is temporarily unreachable?

Any resource server relying purely on introspection cannot make a confident decision and typically must reject the request or fall back to a cached result if one is available and still within its trusted window. This is exactly why introspection introduces an availability dependency that must be planned for.

Q4Can any application call the introspection endpoint?

No. Keycloak requires the calling application to authenticate itself with valid client credentials before it will reveal anything about a token, preventing anonymous probing.

Q5Does introspection reveal the user’s password?

Never. The introspection response describes the token’s status and associated metadata such as username, scopes, and expiry — it has no relationship to and never exposes the original password used at login.

Q6Is caching introspection results considered safe?

It is a widely accepted practice as long as the cache duration is short and proportionate to how quickly a revocation needs to take effect for that particular application’s risk level.

14Summary and Key Takeaways

Token introspection turns a static, unreadable, or potentially outdated piece of proof into a live, trustworthy answer by putting Keycloak in the position of an authoritative source that every resource server can consult in real time. It trades a small amount of network latency for a significant gain in control — instant revocation, centralized policy, and simplified resource servers that no longer need to understand cryptography or session storage themselves. Used thoughtfully, with proper caching, monitoring, and credential hygiene, it becomes one of the most dependable building blocks of a secure, modern identity architecture.

Key Takeaways

  • Introspection answers one question in real time — is this token still active, and what does it allow right now.
  • It matters most for opaque tokens — which carry no readable information and cannot be verified any other way.
  • It follows an open standard — RFC 7662 — so the same mental model applies across compliant identity providers, not just Keycloak.
  • It trades latency for immediacy — a network call in exchange for instant revocation and centralized trust.
  • It requires its own security discipline — HTTPS everywhere, protected client secrets, and never logging raw tokens.
  • Gateway-level introspection scales better than every microservice calling Keycloak independently.
  • A valid token is not the same as permission — resource servers must still apply their own authorization logic after introspection confirms the token is active.