Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: A Single-Page App with PKCE

Build the Authorization Code with PKCE flow for a single-page app against a Keycloak client, with a runnable in-memory mock server that shows every request and check.

Browser apps cannot keep secrets: anything shipped in JavaScript can be read. That is why single-page applications use a public client with the Authorization Code flow plus PKCE (Proof Key for Code Exchange, pronounced "pixie"). In this project you configure the Keycloak side, then build the client logic of the flow step by step against a runnable in-memory mock of the server, so you can see exactly which values travel where and which checks stop an attacker.

Keycloak cannot run on this site. The mock server below is a stand-in written for teaching: it implements only the PKCE check and a toy token, not Keycloak's real behaviour. The Keycloak console steps are described for a recent version.

Step 1: Configure the client in Keycloak

In your realm, Clients > Create client:

  1. Client type: OpenID Connect. Client ID: spa-demo.
  2. Capability config: leave Client authentication off (public client). Keep Standard flow on. Turn Direct access grants and Implicit flow off.
  3. Login settings:
    • Valid redirect URIs: the exact callback, for example https://app.example.com/callback (avoid wildcards).
    • Valid post logout redirect URIs: https://app.example.com/.
    • Web origins: https://app.example.com so the browser may call the token endpoint (CORS).
  4. Advanced > Advanced settings: set Proof Key for Code Exchange Code Challenge Method to S256 so Keycloak rejects requests without PKCE.

That is the whole server side. Everything else lives in the browser app.

Step 2: The flow

sequenceDiagram
    participant B as SPA (browser)
    participant K as Keycloak
    B->>B: Create code_verifier, compute code_challenge (S256), create state
    B->>K: GET /auth?client_id&redirect_uri&response_type=code&code_challenge&state
    K->>B: Login page, then redirect to callback with code and state
    B->>B: Check state matches
    B->>K: POST /token (code, code_verifier, redirect_uri)
    K->>K: SHA-256(code_verifier) equals stored code_challenge?
    K-->>B: access token (and id token)

The challenge goes out in the front channel; the verifier proves possession only at the token endpoint.

The point of PKCE: if an attacker steals the authorization code from the redirect, they cannot redeem it, because they lack the random code_verifier that only your app knows.

Step 3: Make the verifier and challenge

The verifier is a high-entropy random string (43 to 128 characters from the unreserved set). The challenge is the base64url of the SHA-256 hash of the verifier:

JS PKCE verifier and challenge

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

No output.

Step 4: Run the whole flow against a mock

The mock below registers one client, issues a code bound to the challenge, and redeems it only when the verifier hashes to the stored challenge. Read it top to bottom: the SPA part is the code you would write in a real app (using fetch and location).

JS End-to-end PKCE flow against a mock server

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

No output.

Step 5: What a real app adds

Real code has the same skeleton, plus details the mock skips:

  • Keep the verifier and state until the callback. sessionStorage is the usual place for a tab-scoped flow.
  • Read code and state from location.search in the callback route, clean the URL afterwards with history.replaceState.
  • Call the real token endpoint POST /realms/<realm>/protocol/openid-connect/token with grant_type=authorization_code, client_id, code, redirect_uri, and code_verifier.
  • Keep the access token in memory where possible; avoid long-lived storage because any XSS can read localStorage.
  • Refresh tokens: prefer short access tokens with refresh token rotation, or use silent renewal supported by your library.
  • Handle logout with the end-session endpoint and id_token_hint, then redirect to a registered post logout URI.
  • Use a maintained library (such as the official keycloak-js adapter or a general OIDC client) rather than your own implementation. The code above is for understanding.

Test checklist

  1. Login works and returns to the exact callback URL.
  2. Changing the state value makes the app abort.
  3. Reusing the same code fails.
  4. A request without a code challenge is rejected because PKCE is enforced.
  5. The access token is sent as Authorization: Bearer to your API, which validates it (next project).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a SPA a public client?

    Anything shipped to the browser can be read, so no secret can be stored there.
  2. 2. What does the token endpoint compare with the stored code challenge?

    Keycloak hashes the verifier with S256 and checks it against the challenge from the authorization request.
  3. 3. Which value defends against forged callbacks?

    The app generates state, stores it, and compares it on the callback.
  4. 4. Which flow should be turned off for a modern SPA client?

    Implicit flow returns tokens in the URL and is considered obsolete; Authorization Code with PKCE replaces it.

Summary

  • SPAs use a public client with Authorization Code and PKCE; enforce S256 in the client settings.
  • The challenge goes out first; the verifier proves ownership at the token request.
  • Check state, use exact redirect URIs, and keep tokens short lived.
  • Use a maintained library in real projects.

Next: Project: A JWT Verifier for Your API