Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท OAuth2 and OIDC Flows

Authorization Code Flow with PKCE in Keycloak

Follow the authorization code flow with PKCE step by step: request parameters, state and nonce, code exchange, Keycloak client settings, and a runnable PKCE and state demo.

The authorization code flow with PKCE is how nearly every user-facing application should sign in with Keycloak. The browser never carries tokens in a URL: it only carries a short-lived, single-use code, which the application swaps for tokens over a direct connection. PKCE (Proof Key for Code Exchange, pronounced "pixie") makes a stolen code useless. This lesson walks through every step and then lets you compute a real PKCE challenge.

The flow

sequenceDiagram
  participant U as User (browser)
  participant A as Application
  participant K as Keycloak
  A->>A: make code_verifier, state, nonce
  A->>U: redirect to /auth with code_challenge
  U->>K: GET /auth?response_type=code&client_id=...
  K->>U: login form
  U->>K: credentials
  K->>U: redirect to redirect_uri?code=...&state=...
  U->>A: GET /callback?code=...&state=...
  A->>K: POST /token (code, code_verifier)
  K->>A: access, ID and refresh tokens

Only the back-channel POST carries the verifier and receives the tokens.

Step 1: the authorization request

The app redirects the browser to:

TEXT
GET /realms/demo/protocol/openid-connect/auth
  ?response_type=code
  &client_id=demo-web
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
  &scope=openid%20profile%20email
  &state=Xk3f...random
  &nonce=9Qz...random
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
Parameter Role
response_type=code Ask for an authorization code
client_id, redirect_uri Which client; where to return (must match a registered URI exactly)
scope What to ask for; openid makes it an OIDC login
state A random value the app checks on return; defends against CSRF and mixes up responses
nonce A random value Keycloak copies into the ID token; the app checks it to stop token replay
code_challenge, code_challenge_method The PKCE challenge: BASE64URL(SHA-256(code_verifier)) and S256

Optional but useful: prompt=login (force re-authentication), prompt=none (silent check), login_hint, kc_idp_hint (jump to a brokered identity provider), max_age, acr_values.

Step 2: login

Keycloak runs the realm's browser authentication flow. If an SSO cookie exists, the user is not asked again. After authentication (and any required actions or consent) Keycloak redirects to the redirect_uri with code and the same state.

Step 3: the callback

The app must:

  1. Verify that state equals the value it stored for this browser session. If not, stop.
  2. Handle an error parameter (access_denied, login_required) instead of code.
  3. Exchange the code immediately: codes live for about a minute and work once.

Step 4: the token request

Terminal
curl -s -X POST http://localhost:8080/realms/demo/protocol/openid-connect/token \
  -d grant_type=authorization_code \
  -d client_id=demo-web \
  -d code="$CODE" \
  -d redirect_uri=https://app.example.com/callback \
  -d code_verifier="$VERIFIER"

A confidential client adds its credentials (client_secret, or an assertion). A public client sends only client_id. The response contains access_token, id_token, refresh_token and expiry values. The app then validates the ID token (signature, iss, aud, exp, and that nonce matches) before treating the user as signed in.

Why PKCE works

Without PKCE, anyone who intercepts the code (a malicious app registered for the same custom URL scheme on a phone, a browser extension, a log file) can exchange it. With PKCE the app creates a random code_verifier first and sends only its hash (code_challenge) in the browser request. At the token request it reveals the verifier; Keycloak hashes it and compares. A thief holding only the code lacks the verifier. PKCE is therefore useful even for confidential clients.

Client settings in Keycloak

In Clients > (client) > Settings:

  • Client authentication Off for SPAs and mobile apps (public), On for server apps.
  • Standard flow On. Turn Implicit flow and Direct access grants Off.
  • Valid redirect URIs: exact URLs. For native apps use claimed HTTPS links or loopback redirects (http://127.0.0.1:port/), not custom schemes when avoidable.
  • Web origins: the exact origin of a SPA (or + to reuse the redirect URIs) so browsers can call the token endpoint.

In Advanced > Advanced settings set Proof Key for Code Exchange Code Challenge Method to S256. That makes Keycloak reject authorization requests without a valid S256 challenge, enforcing the protection server-side.

Logout

To sign the user out of Keycloak as well, redirect the browser to the end_session_endpoint:

TEXT
/realms/demo/protocol/openid-connect/logout
  ?id_token_hint=<id token>
  &post_logout_redirect_uri=https%3A%2F%2Fapp.example.com%2F

The post_logout_redirect_uri must be listed in the client's Valid post logout redirect URIs. If you skip the Keycloak logout and only clear your own session, the SSO cookie remains and the next click on "Sign in" logs the user straight back in.

Compute PKCE for real (stand-in)

This block uses Node's real SHA-256 to build a verifier, challenge, state and nonce exactly as an app would. The values are random, so only the checks are printed. It also verifies the challenge with the RFC 7636 test vector, so you can see the math is genuine, although this is only a client-side demo, not Keycloak.

Node.js PKCE verifier and challenge

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.

Callback validation (stand-in)

The most common bugs are in the callback. This stand-in implements the checks a correct app performs, so you can see each failure message.

Node.js Stand-in: validate the callback

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.

Checklist

  1. Generate a fresh state, nonce and code_verifier for every login.
  2. Use S256, and enforce it in the client's advanced settings.
  3. Register exact redirect URIs; never wildcards in production.
  4. Check state on return; validate the ID token and nonce after the exchange.
  5. Prefer a maintained OIDC library (for example oidc-client-ts, keycloak-js, Spring Security, Passport, Authlib) over hand-written code; the stand-ins are for learning.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the code_challenge contain?

    The app sends the hash up front and reveals the verifier only when redeeming the code.
  2. 2. What is the purpose of the state parameter?

    The app stores a random state and requires the same value to come back.
  3. 3. An attacker steals the authorization code from the redirect URL. Why can't they redeem it when PKCE is used?

    Keycloak hashes the presented verifier and compares it with the stored challenge.
  4. 4. Which Keycloak setting makes S256 PKCE mandatory for a client?

    With that method set, requests lacking a valid S256 challenge are rejected.

Summary

  • The browser carries only a one-time code; the app swaps it for tokens on the back channel.
  • state protects against CSRF, nonce against ID-token replay, PKCE against stolen codes.
  • Configure public or confidential client, standard flow, exact redirect URIs and S256 enforcement.
  • Validate the ID token after exchange; log out through the end-session endpoint with a registered redirect.
  • Use a vetted library in real applications.

Next: Tokens and JWT Claims