Skip to content
Hands-on IT IT Drills

Day 3: OIDC and Tokens

Goal: Create a client, fetch and read tokens in three ways, use the OpenID Connect endpoints and walk through the authorization code flow with PKCE by hand. · Duration: approx. 75 min · Prerequisite: Day 2

Briefing

  • A client is an application that Keycloak knows. Confidential means: It has a secret and runs on a server.
  • Flows: Authorization code with PKCE for everything with a browser, client credentials for machines, password (direct access grant) only for tests.
  • A login returns three tokens: access token (for APIs), ID token (for the application: who is logged in), refresh token (for new access tokens).
  • Keycloak signs with RS256; the public keys are in the JWKS (/protocol/openid-connect/certs).
 Browser ─► /auth?…&code_challenge=…  ─► Login ─► Redirect with ?code=…
 Application ─► /token  code + code_verifier + secret ─► access, ID, refresh token
 API ─► checks signature with the JWKS, without asking Keycloak

Drill 1: The Client notes-cli

source ~/kc-lab/setup/env.sh
mkdir -p ~/kc-lab/tag03 && cd ~/kc-lab/tag03
kclogin
kcadm create clients -r lab -s clientId=notes-cli -s enabled=true \
  -s publicClient=false -s secret=lab-client-secret-123 \
  -s standardFlowEnabled=true -s directAccessGrantsEnabled=true \
  -s serviceAccountsEnabled=true -s 'redirectUris=["http://localhost:9999/*"]'
kcadm get clients -r lab -q clientId=notes-cli --fields clientId,publicClient,\
standardFlowEnabled,directAccessGrantsEnabled,serviceAccountsEnabled

Expected (abridged):

Logging into http://localhost:8080 as user kcadmin of realm master
Created new client with id '9e9423dd-…'
[ {
  "clientId" : "notes-cli",
  "publicClient" : false,
  "standardFlowEnabled" : true,
  "directAccessGrantsEnabled" : true,
  "serviceAccountsEnabled" : true
} ]

Three flows on one client, for the lab only. In production, every application gets its own client with exactly the one flow it needs.

Save your progress? Sign up for free

Drill 2: Fetching and Reading a Token

token from env.sh uses the password grant. First the whole response, abridged:

OIDC=$KC_URL/realms/lab/protocol/openid-connect
R=$(curl -s -d grant_type=password -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d username=anna -d password=lab-user-pw-123 \
  -d scope=openid $OIDC/token)
echo "$R" | jq -c 'with_entries(if (.key | test("token$")) then
  .value = (.value | .[0:12] + "…") else . end)'
TOKEN=$(echo "$R" | jq -r .access_token)

Expected (abridged):

{"access_token":"eyJhbGciOiJS…","expires_in":120,"refresh_expires_in":1800,
"refresh_token":"eyJhbGciOiJI…","token_type":"Bearer","id_token":"eyJhbGciOiJS…",
"not-before-policy":0,"session_state":"…","scope":"openid profile email"}

The access token is valid for 120 seconds (challenge from Day 1), the refresh token for 30 minutes. Now look inside:

echo "$TOKEN" | jq -R 'split(".")[0] | @base64d | fromjson'
jwt "$TOKEN" | jq '{iss, aud, azp, typ, preferred_username, email, scope,
  roles: .realm_access.roles, gueltig: (.exp - .iat)}'

Expected (abridged, values will differ on your machine):

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "7W_UiON_Ted47k_XNQtdRHxugodLEjknJMcM9x8Up90"
}
{
  "iss": "http://kc.192.168.64.7.sslip.io:8080/realms/lab",
  "aud": "account",
  "azp": "notes-cli",
  "typ": "Bearer",
  "preferred_username": "anna",
  "email": "[email protected]",
  "scope": "openid profile email",
  "roles": [
    "offline_access",
    "notes-lesen",
    "default-roles-lab",
    "uma_authorization",
    "notes-schreiben"
  ],
  "gueltig": 120
}

iss is the name from KC_URL, azp the client that fetched the token, and realm_access.roles holds the effective roles from Day 2. gueltig (valid) is the lifetime in seconds. Keep aud: account in mind for Drill 4.

Save your progress? Sign up for free

Drill 3: Keys and User Data

curl -s $OIDC/certs | jq -r '.keys[] | [.kid, .alg, .use] | @tsv'
curl -s -H "Authorization: Bearer $TOKEN" $OIDC/userinfo | jq -c .

Expected (abridged):

7W_UiON_Ted47k_XNQtdRHxugodLEjknJMcM9x8Up90 RS256   sig
RKshEJsdujnto2iWso-r2Z4n4V325acUNKeZdPoC0Lw RSA-OAEP    enc
{"sub":"86ed1f4c-…","email_verified":true,"name":"Anna Lab","preferred_username":"anna",
"given_name":"Anna","family_name":"Lab","email":"[email protected]"}

The kid of the signing key is the same as in the token’s header. That is exactly how notes-api finds the matching key (Day 0, challenge). userinfo returns the profile data for the token.

Save your progress? Sign up for free

Drill 4: Introspection and the Audience

An API can also ask Keycloak whether a token is still valid:

curl -s -u notes-cli:lab-client-secret-123 -d token=$TOKEN $OIDC/token/introspect \
  | jq -c '{active}'
docker compose -f ~/kc-lab/keycloak/compose.yaml logs --since 1m keycloak 2>&1 \
  | grep -o 'reason="[^"]*"' | tail -1

Expected:

{"active":false}
reason="Client 'notes-cli' is not in the token audience"

The token is fresh, and still active: false. Keycloak 26 only answers introspection if the requesting client is in the token’s audience (aud). Here there is only account. You add an audience for your own API on Day 5. Only the event in the log reveals the reason, not the response itself.

Save your progress? Sign up for free

Drill 5: Machines and Refreshing

A service without a user gets a token with its own secret:

CC=$(curl -s -d grant_type=client_credentials -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 $OIDC/token | jq -r .access_token)
jwt "$CC" | jq -c '{preferred_username, azp, roles: .realm_access.roles}'

Expected:

{"preferred_username":"service-account-notes-cli","azp":"notes-cli","roles":
["offline_access","default-roles-lab","uma_authorization"]}

The service account is a user of its own with its own roles. And when an access token expires, the application exchanges the refresh token for a new one:

RT=$(echo "$R" | jq -r .refresh_token)
N=$(curl -s -d grant_type=refresh_token -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d refresh_token=$RT $OIDC/token)
echo "$N" | jq -c '{expires_in, refresh_expires_in}'
curl -s -o /dev/null -w 'logout %{http_code}\n' -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 \
  -d refresh_token=$(echo "$N" | jq -r .refresh_token) $OIDC/logout
curl -s -d grant_type=refresh_token -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 \
  -d refresh_token=$(echo "$N" | jq -r .refresh_token) $OIDC/token | jq -c .

Expected:

{"expires_in":120,"refresh_expires_in":1800}
logout 204
{"error":"invalid_grant","error_description":"Session not active"}

Logout ends the session in Keycloak; the refresh token is worthless afterwards. The access token already issued remains valid until its exp if an API only checks it by signature. That is why short-lived access tokens matter.

Save your progress? Sign up for free

Drill 6: Authorization Code with PKCE by Hand

This is how a web application logs in. First a random code verifier and from it the code challenge (SHA-256, Base64url):

V=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-64)
C=$(printf %s "$V" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
echo "${#V} ${#C}"
echo "$OIDC/auth?client_id=notes-cli&response_type=code&scope=openid\
&redirect_uri=http://localhost:9999/cb&code_challenge=$C&code_challenge_method=S256\
&state=xyz"

Expected (abridged):

63 43
http://kc.192.168.64.7.sslip.io:8080/realms/lab/protocol/openid-connect/auth?client_id=…

Open the URL in the laptop’s browser and log in as anna. Keycloak redirects to http://localhost:9999/cb?…; nothing runs there, and the browser shows an error. What matters is the address bar. Copy it quickly (the code is valid for one minute) into the VM:

CB='http://localhost:9999/cb?state=xyz&session_state=…&code=…'
echo "$CB" | grep -o '[?&]state=[^&]*'
CODE=$(echo "$CB" | grep -o 'code=[^&]*' | cut -d= -f2)
tausch() {
  curl -s -d grant_type=authorization_code -d client_id=notes-cli \
    -d client_secret=lab-client-secret-123 -d code=$CODE \
    -d redirect_uri=http://localhost:9999/cb -d code_verifier="$1" $OIDC/token
}
tausch "$V" | jq -c '{token_type, expires_in, scope, id_token: (.id_token != null)}'
tausch "$V" | jq -c .

Expected:

?state=xyz
{"token_type":"Bearer","expires_in":120,"scope":"openid profile email","id_token":true}
{"error":"invalid_grant","error_description":"Code not valid"}

state comes back unchanged; the application uses it to check that the response belongs to its request. The code is valid exactly once. And without the right verifier, an intercepted code is of no use:

CB='…'   # new login, new address bar
CODE=$(echo "$CB" | grep -o 'code=[^&]*' | cut -d= -f2)
tausch falsch-falsch-falsch-falsch-falsch-falsch-falsch-1234 | jq -c .

Expected:

{"error":"invalid_grant","error_description":"PKCE verification failed: Code mismatch"}

Save your progress? Sign up for free

Checkpoint

jwt "$(token)" | jq -r .preferred_username

Expected: token from env.sh works.

anna
jwt "$(token ben lab-user-pw-456)" \
  | jq -c '.realm_access.roles | map(select(startswith("notes")))'

Expected: ben’s token contains only the read role.

["notes-lesen"]
curl -s $OIDC/certs | jq '[.keys[] | select(.use == "sig")] | length'

Expected: one signing key.

1

Challenge

Show that an expired access token fails at userinfo, even though its signature is still correct.

Hint: You know the lifetime; userinfo asks the session in Keycloak.

Solution

T=$(token)
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $T" $OIDC/userinfo
sleep 125
curl -s -w ' %{http_code}\n' -H "Authorization: Bearer $T" $OIDC/userinfo

Expected:

200
 401

At userinfo, Keycloak also checks exp and answers with 401 without a body; the WWW-Authenticate header names the reason (curl -i). An API that checks tokens itself must do the same; notes-api allows at most 30 seconds of clock skew.

Save your progress? Sign up for free

Enterprise Note

  • No password grant: OAuth 2.1 removes it. Applications with users use the authorization code flow with PKCE, machines use client credentials.
  • Public clients (single-page apps, mobile) have no secret; there, PKCE is the only protection of the code and mandatory.
  • Tokens in the browser do not belong in localStorage. Better: a backend holds the tokens, the browser only a session cookie (Day 4 with oauth2-proxy).
  • Signature check or introspection: Checking via JWKS is fast and needs no round trip, but does not detect a logout before exp. Introspection detects it and costs a round trip to Keycloak per request.