Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท OAuth2 and OIDC Flows

Tokens and JWT Claims: Access, ID and Refresh Tokens in Keycloak

Decode and validate Keycloak access, ID and refresh tokens: JWT structure, standard and Keycloak claims, JWKS signature checks, lifetimes, introspection and refresh rotation.

Every Keycloak integration comes down to tokens. If you can read them, validate them and know what each claim means, debugging login problems becomes straightforward. This lesson dissects a token, shows what a resource server must verify, and runs a real RS256 signing and verification, the same mechanism Keycloak uses, on sample keys generated on the spot.

The three tokens

Token Audience Contents Typical life
Access token The API Identity, roles, scopes; typ: Bearer Minutes
ID token The client app Who the user is, how and when they authenticated; typ: ID Minutes
Refresh token Keycloak A signed handle to the session; typ: Refresh Up to the session limits

Keycloak issues all three as JWTs. (A JWT access token is the Keycloak default; some systems use opaque tokens checked by introspection instead.)

JWT anatomy

A JSON Web Token has three base64url parts separated by dots: header.payload.signature.

TEXT
eyJhbGciOiJSUzI1NiIs...   header
.eyJleHAiOjE3MzAw...      payload (claims)
.Qm9nd...                 signature

The header names the algorithm (alg: RS256), the type and the key ID (kid). The payload is a JSON object of claims. The signature covers header and payload using the realm's private key. Anyone can read a JWT (base64 is not encryption), so never put secrets in claims. Only the signature protects integrity.

Claims in a Keycloak access token

JSON
{
  "exp": 1760000300,
  "iat": 1760000000,
  "auth_time": 1759999990,
  "jti": "5d2a...",
  "iss": "https://id.example.com/realms/demo",
  "aud": "invoice-api",
  "sub": "f1a2b3c4-....",
  "typ": "Bearer",
  "azp": "demo-web",
  "sid": "9c1e...",
  "acr": "1",
  "allowed-origins": ["https://app.example.com"],
  "realm_access": { "roles": ["customer"] },
  "resource_access": { "invoice-api": { "roles": ["read"] } },
  "scope": "openid profile email",
  "email_verified": true,
  "preferred_username": "alice",
  "email": "[email protected]"
}
Claim Meaning
iss Issuer: the realm URL. Must match what the API expects.
sub Subject: the user's unique, stable ID (a UUID). Use it as the key, not the username or email, which can change.
aud Audience: who the token is meant for. An API must reject tokens whose aud does not include it.
azp Authorized party: the client that requested the token.
exp, iat, nbf Expiry, issued-at, not-before (seconds since 1970).
jti Unique token ID (useful for replay checks and revocation lists).
sid Session ID, ties tokens to the SSO session.
scope The granted scopes.
typ Token type: Bearer, ID, Refresh.
acr, auth_time How strongly and when the user authenticated.

The ID token adds nonce, at_hash and profile claims; the userinfo endpoint returns the same profile data on demand.

What a resource server must validate

  1. Signature with the public key from the realm's JWKS (/realms/demo/protocol/openid-connect/certs), selected by kid.
  2. Algorithm: accept only the expected one (RS256). Never trust the header's alg, and never accept none.
  3. iss equals the realm URL you configured.
  4. exp (and nbf) with a few seconds of clock leeway.
  5. aud includes your API. In Keycloak, the audience is added by an Audience mapper or the audience resolve mapper based on client roles; a token with no aud for your API should be rejected.
  6. Optionally typ is Bearer, so ID and refresh tokens cannot be used as access tokens.

Use your platform's maintained library (Spring Security, jose for Node, PyJWT, Microsoft.IdentityModel). Fetch and cache the JWKS, and re-fetch when you meet an unknown kid.

Introspection and revocation

JWT validation is local and fast, but cannot know a token was revoked. For high-value calls use token introspection (POST .../token/introspect, authenticated as a client), which asks Keycloak whether the token is still active. Logout and session revocation invalidate refresh tokens immediately; access tokens die at exp, which is why you keep them short. The Not before policy (Clients > Advanced, and Sessions > Revocation) can invalidate older tokens per client or realm.

Refresh tokens

When the access token expires, the app posts grant_type=refresh_token with the refresh token and gets a fresh set. In Realm settings > Tokens, Revoke Refresh Token makes refresh tokens single-use (rotation): each refresh returns a new refresh token and a reused old one invalidates the session, detecting theft. The refresh token cannot outlive the session's idle and maximum limits. Offline tokens (scope offline_access) survive logout and are for long-running background access, and are stored server side as offline sessions.

Real RS256 in miniature (stand-in)

This block creates an RSA key pair, signs a JWT with RS256, builds a JWKS-style public key set and validates the token with all the checks above. The key is generated fresh at run time and is not a Keycloak key. The outputs shown are only the check results, so they are stable.

Node.js Sign and validate an RS256 JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Decode a token (stand-in)

Reading a token locally is a key debugging skill. This stand-in decodes a hand-made sample token (it is not signed by any real server) and prints human-friendly times.

Node.js Decode and describe a JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Trusting a token because it decodes; only a verified signature counts.
  • Using email or preferred_username as a database key instead of sub.
  • Skipping the aud check, so a token meant for another API is accepted ("confused deputy").
  • Long access-token lifetimes (hours) to avoid refresh logic.
  • Storing refresh tokens in localStorage of a SPA; prefer a BFF or keep tokens in memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which claim should you use as a stable user key in your database?

    sub is the unique, immutable user ID. Usernames and emails can change.
  2. 2. Where does an API get the public key to verify a Keycloak token signature?

    The JWKS lists the realm's public signing keys; kid in the header selects the right one.
  3. 3. Is the content of a JWT access token secret?

    Base64url is encoding, not encryption. Treat the token as a bearer secret and keep sensitive data out of it.
  4. 4. What does refresh-token rotation (Revoke Refresh Token) accomplish?

    Single-use refresh tokens limit damage from a stolen token.

Summary

  • Keycloak issues JWT access, ID and refresh tokens; the payload is readable, the signature protects it.
  • Validate signature (JWKS and kid), algorithm, iss, exp, aud and typ in every API.
  • Use sub as the user key; roles live in realm_access and resource_access.
  • Keep access tokens short; use introspection for sensitive operations and rotate refresh tokens.
  • Prefer maintained libraries; the stand-ins here show the mechanics.

Next: Client Credentials and Service Accounts