How-To Guide

How to Implement OAuth 2.0 Token Introspection

Validate opaque access tokens with the introspection endpoint, cache the results, and reason about the trade-offs versus JWT validation.

On this page

  1. Introduction
  2. Opaque Tokens and Why You Introspect
  3. Calling the Introspection Endpoint
  4. Caching Introspection Results Safely
  5. Introspection Versus JWT Validation
  6. Security of the Introspection Call
  7. Failure Modes and Availability
  8. Common Pitfalls and Conclusion

Introduction

Not every access token is a self-contained JWT. Providers issue opaque tokens that carry no readable claims, and a resource server cannot validate them by checking a signature. Instead it asks the authorization server whether the token is active using the OAuth 2.0 introspection endpoint (RFC 7662). The response says whether the token is valid, when it expires, and for whom it was issued. Introspection is authoritative but adds a network call per request, so the design challenge is caching it safely without losing the revocation guarantees introspection exists to provide.

Opaque Tokens and Why You Introspect

A JWT can be validated offline: the resource server checks the signature and the claims and decides locally. An opaque token has no such structure; it is a random string whose meaning lives in the authorization server’s database. The only way to know what it grants is to ask. That is what introspection does.

Introspection is also how you see revocation immediately. A revoked JWT stays cryptographically valid until it expires, so revocation needs a denylist or short lifetimes. An opaque token introspected on each use reflects revocation the moment it happens, which is why some systems prefer opaque tokens despite the extra call.

POST /oauth/introspect HTTP/1.1
Host: auth.example.com
Authorization: Basic <base64(client_id:client_secret)>
Content-Type: application/x-www-form-urlencoded

token=2YotnFZFEjr1zCsicMWpAA&token_type_hint=access_token

Calling the Introspection Endpoint

The resource server authenticates to the introspection endpoint with its own client credentials, not the user’s token. It sends the token to inspect and an optional token_type_hint. The response is a JSON object with an active boolean and, when active, the scope, client_id, username, token_type, exp and iat. When inactive, the spec says the response should be just {“active”: false}, without leaking why.

Treat a non-200 response or a malformed body as a failure, not as “inactive”. An outage at the authorization server must not silently log everyone out unless you have decided that failing closed is the right call for the endpoint in question. Make that decision explicitly per resource.

interface Introspection { active: boolean; scope?: string; sub?: string; client_id?: string; exp?: number; }

export async function introspect(token: string): Promise<Introspection> {
  const res = await fetch(INTROSPECT_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: 'Basic ' + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64'),
    },
    body: new URLSearchParams({ token, token_type_hint: 'access_token' }),
  });
  if (!res.ok) throw new Error('introspection_unavailable: ' + res.status); // fail, don't logout
  return res.json() as Promise<Introspection>;
}

Caching Introspection Results Safely

A network call per request is expensive, so cache the result. The safe cache key is a hash of the token, never the token itself, so a cache dump does not leak credentials. Cache only active results, and cache them for the shorter of a fixed maximum and the token’s remaining lifetime, so a token does not outlive its expiry in the cache.

Revocation is the hard part: a cached active result keeps a revoked token working until the entry expires. Bound that window with a short TTL, and, if the provider offers revocation webhooks or a revocation list, use them to evict eagerly. When revocation speed matters, keep the TTL low; when throughput matters more, accept a slightly longer window and document it.

import { createHash } from 'node:crypto';

function cacheKey(token: string) { return createHash('sha256').update(token).digest('hex'); }

async function checkToken(token: string): Promise<boolean> {
  const key = cacheKey(token);
  const hit = cache.get(key);
  if (hit) return true;                     // only active results cached

  const info = await introspect(token);
  if (!info.active) return false;           // never cache inactive
  const ttl = Math.min(60_000, (info.exp ?? 0) * 1000 - Date.now());
  if (ttl > 0) cache.set(key, true, ttl);   // never longer than the token lives
  return true;
}

Introspection Versus JWT Validation

Choose based on where the truth must live. JWT validation is local and fast but cannot reflect revocation until expiry; introspection is authoritative and reflects revocation immediately but costs a call and depends on the authorization server being up. Many systems do both: validate the JWT’s signature and claims locally for cheap checks, and introspect only for high-risk operations such as payment or admin actions.

A hybrid that works well is short-lived access tokens plus local JWT validation, with introspection for the operations that must honour revocation instantly. The shorter the token lifetime, the less the local validation diverges from the truth, and the less you pay for introspection.

# decision table
offline JWT validation   fast, stateless, revocation delayed until exp
introspection            authoritative, immediate revocation, +1 call
hybrid (recommended)     validate JWT locally; introspect high-risk ops
short-lived tokens       make offline validation almost as fresh

Security of the Introspection Call

Protect the client credentials used to call introspection as carefully as any secret; a leaked pair lets an attacker inspect any token. Call the endpoint over TLS, and never log the token being inspected, because the token is a live credential. Hash tokens before using them as cache keys or log correlation ids.

Rate-limit and monitor the introspection call. A spike may mean a retry storm or an attacker probing tokens. Also guard against token substitution: the response’s client_id and scope must match what you expected for the endpoint, so a token minted for a different audience is rejected even if it is active.

Failure Modes and Availability

If the authorization server is unreachable, decide per endpoint whether to fail open or closed. Public, low-risk reads might fail open with a short grace window; payments and admin actions must fail closed. Encode this per route rather than globally, because a single global choice is either too permissive or too strict for some endpoints.

Combine introspection with the token’s own expiry even while failing open: reject expired tokens locally regardless, and reject tokens whose audience does not match. That keeps the fail-open window bounded by the token lifetime rather than indefinite.

Common Pitfalls and Conclusion

Do not cache the token in plaintext. Do not cache inactive results, which wastes memory and can pin a decision after the token is later reactivated. Do not treat an outage as authorization. Do not forget to check audience and scope after a successful introspection. And do not introspect on every request without measuring the added latency and availability cost.

Introspection answers the question a resource server must ask of an opaque token: is this credential active, and for whom. Call it with the resource server’s credentials, cache by a hash of the token with a TTL bounded by expiry, evict on revocation when possible, and choose fail-open or fail-closed per endpoint. Combined with short-lived tokens, it gives immediate revocation without paying a call on every request.

Sources: RFC 7662: OAuth 2.0 Token Introspection, RFC 6750: Bearer Token Usage, OAuth 2.0 Security Best Current Practice.

FAQ

Can I cache introspection results?
Yes, but only active ones, keyed by a hash of the token, with a TTL bounded by the shorter of a fixed maximum and the token's remaining lifetime. Caching extends the window in which a revoked token still works, so keep the TTL short when revocation speed matters.
Should I use introspection or JWT validation?
Use local JWT validation for cheap, high-volume checks and introspection for operations that must honour revocation immediately, such as payments or admin actions. Short-lived tokens make offline validation almost as fresh as introspection.

Related Examples