TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › PKCE, Worked Through ExcelTAD's TAD Sign-In

PKCE, Worked Through ExcelTAD's TAD Sign-In

A single-page application has no backend to keep a client secret in. Anything shipped to the browser is public, so the secret-based code exchange of the previous lesson doesn't work, and for years such apps used the implicit flow, with tokens in the URL. PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixy") replaced it: the client invents a one-time secret for each sign-in, sends only its hash at the start and the secret itself at the end, so a stolen authorization code is useless to anyone else. This site is a worked example. ExcelTAD is a static site with no backend, and its optional sign-in to TAD, the ecosystem's identity server, is a public OAuth 2.0 / OpenID Connect client with PKCE. This lesson walks through what its code (src/account/tad.ts, documented in docs/TAD_ACCOUNT.md in the repository) actually does, and why each step is there.

Definitions (RFC 7636)

  • code_verifier: a high-entropy random string, 43 to 128 characters of [A-Z a-z 0-9 - . _ ~], created per authorization request and kept by the client.
  • code_challenge: BASE64URL(SHA-256(code_verifier)) for method S256. (Method plain sends the verifier itself and should not be used.)
  • The binding: the AS stores the challenge with the authorization code; the token request must include the verifier, and the AS checks that its hash equals the stored challenge.

The S256 transform, checked against the RFC

RFC 7636 Appendix B gives a verifier and its challenge. This is the same computation as ExcelTAD's pkceChallenge() (WebCrypto's SHA-256 and a Base64url encoder), run in Node:

js · try it yourself
const b64url = (bytes) =>
  btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

async function pkceChallenge(verifier) {
  return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
}

const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';   // RFC 7636 Appendix B
const challenge = await pkceChallenge(verifier);
console.log('challenge:', challenge);
console.log('matches RFC 7636:', challenge === 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM');

// ExcelTAD draws 48 random bytes for the verifier and 32 for state and nonce:
const randomString = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
console.log('verifier length:', randomString(48).length, '| state length:', randomString(32).length, '(256 bits)');
challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
matches RFC 7636: true
verifier length: 64 | state length: 43 (256 bits)

48 random bytes become a 64-character verifier (384 bits), inside the RFC's 43–128 range; state and nonce are 32 random bytes each, 256 bits, well above TAD's requirement of at least 128.

Why an intercepted code is worthless

The toy below plays the authorization server's side. A malicious app on the same device, a leaked log or a Referer header gives an attacker the code; without the verifier, the exchange fails.

python · try it yourself
import base64, hashlib

def s256(verifier: str) -> str:
    return base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()

STORED = {}     # code -> what the AS remembered at /authorize

def authorize(client_id, redirect_uri, code_challenge, method):
    if method != "S256":
        return "400 only S256 is accepted"
    STORED["code-77"] = {"client_id": client_id, "redirect_uri": redirect_uri, "challenge": code_challenge, "used": False}
    return "code-77"

def token(code, client_id, redirect_uri, code_verifier):
    e = STORED.get(code)
    if not e or e["used"] or e["client_id"] != client_id or e["redirect_uri"] != redirect_uri:
        return "invalid_grant"
    if code_verifier is None or s256(code_verifier) != e["challenge"]:
        return "invalid_grant (PKCE verification failed)"
    e["used"] = True
    return "tokens issued"

verifier = "lab-only-verifier-" + "x" * 40              # real clients: 48 CSPRNG bytes, Base64url
code = authorize("exceltad", "https://learn.lab.test/", s256(verifier), "S256")
print("plain method:     ", authorize("exceltad", "https://learn.lab.test/", verifier, "plain"))
print("attacker, no verifier:   ", token(code, "exceltad", "https://learn.lab.test/", None))
print("attacker, guessed one:   ", token(code, "exceltad", "https://learn.lab.test/", "guess"))
print("real client:             ", token(code, "exceltad", "https://learn.lab.test/", verifier))
print("real client, code reused:", token(code, "exceltad", "https://learn.lab.test/", verifier))
plain method:      400 only S256 is accepted
attacker, no verifier:    invalid_grant (PKCE verification failed)
attacker, guessed one:    invalid_grant (PKCE verification failed)
real client:              tokens issued
real client, code reused: invalid_grant

The challenge travels through the browser, but SHA-256 can't be reversed, so seeing it doesn't help. The verifier travels only in the direct token request.

ExcelTAD's sign-in, step by step

TAD's contract for services (SSO_INTEGRATION_REQUIREMENTS.md in TAD Management, requirements R1–R20) fixes most of these choices; the R-numbers below refer to it. On the copy of the site you are reading, sign-in may be switched off: an empty clientId in tad-config.json disables it, and everything works without an account.

Step What tad.ts does Why
Configuration reads issuer, clientId, scopes from /tad-config.json; endpoints come from TAD's discovery document no hard-coded URLs; one build for every deployment
1. Start creates verifier (48 random bytes), state and nonce (32 each) with crypto.getRandomValues, stores them with the page to return to in sessionStorage survives the redirect, scoped to this tab
2. Redirect top-level navigation to authorization_endpoint with response_type=code, client_id, redirect_uri = the site root, scope=openid profile email offline_access appdata profile:write, state, nonce, code_challenge, code_challenge_method=S256 TAD forbids being framed, so no popups or iframes; one fixed redirect URI matched exactly
3. Return at the site root, takes the pending values out of storage, checks state, requires the iss response parameter to equal the configured issuer (RFC 9207), handles error CSRF on the callback; mix-up attacks (a response from another server)
4. Exchange POST to token_endpoint right away (codes live 60 s) with grant_type=authorization_code, code, the same redirect_uri, code_verifier, client_id, and no secret PKCE replaces the client secret
5. ID token header must be alg: RS256, typ: JWT; key found by kid in TAD's JWKS (refetched once on an unknown kid, for key rotation); RS256 signature verified with WebCrypto; iss equal to the configured issuer, aud contains the client id, exp with 60 s of clock-skew leeway, nonce equal to the stored one, a non-empty sub the JWT pitfalls, closed one by one
6. Tokens access token (15 min), refresh token and ID token kept in localStorage; refreshes serialised across tabs with the Web Locks API TAD rotates refresh tokens on each use and revokes the session if an old one is replayed, so two tabs must not refresh at once
Silent SSO on arrival without tokens, one prompt=none round trip, at most once per tab and once per 10 minutes per browser, skipped unless TAD's status endpoint (/api/v1/status) answers ok within 1.5 s signed in everywhere at once, without loops or blocking the site during outages
Sign-out deletes the local tokens, revokes the refresh token at revocation_endpoint, then navigates to end_session_endpoint with id_token_hint, client_id, post_logout_redirect_uri (the site root) and a state checked on return ends the TAD session for every TAD app in the browser

The user is keyed by sub, never by e-mail.

The trade-off: tokens in localStorage

A public client in a browser must keep its tokens somewhere script can reach, so any script running in the site's origin could read them. ExcelTAD's answer is a hard rule (R10): no third-party script ever runs on the main thread. Every engine loaded from a CDN (Pyodide, webR, PGlite, php-wasm and the others) runs in a Web Worker, and every playground, including this course's XSS demos, runs in a sandboxed iframe without allow-same-origin, which has an opaque origin and no access to localStorage. Short access-token lifetimes and refresh-token rotation with reuse detection limit what a stolen token is worth. Sites with a backend often prefer the backend-for-frontend pattern instead: the server does the OAuth flow and the browser holds only an HttpOnly session cookie.

How a PKCE client is tested (detection)

  • Start a sign-in and check that code_challenge_method=S256 is present and that the challenge changes on every attempt.
  • Replay the callback URL (same code and state) in a fresh tab: it must fail (state already consumed, code single-use).
  • Change state, drop iss, or return an iss of another server: the client must refuse.
  • Send an ID token with a wrong aud, nonce, expired exp or alg changed: the client must refuse.

ExcelTAD's browser acceptance test (scripts/qa/tad-sso-check.mjs) runs the TAD acceptance tests that apply to a static site against a local TAD: among them a forged callback (tampered state, a response without iss), refresh-token rotation, a session ended at TAD and single sign-out, plus an optional section through a mock identity provider. The ID-token checks are in validateIdToken() and are reviewed in code rather than by that script.

Pitfalls

  • PKCE without state still leaves the client open to login CSRF unless the verifier is bound to the browser session; keep both.
  • Storing the verifier in localStorage shared by all tabs, or in the URL.
  • Accepting plain at the AS: it lets an attacker who sees the authorization request use the challenge as the verifier.

Practice

1. An attacker sees the full authorization request URL (with code_challenge) and later steals the code. Can they get tokens with S256? With plain?

With S256, no: they would need a preimage of the SHA-256 hash. With plain, yes: the challenge is the verifier.

2. Why does ExcelTAD serialise refresh-token use across tabs with Web Locks?

TAD rotates refresh tokens and treats reuse of an old one as theft, revoking the whole session. Two tabs refreshing with the same token at once would look like reuse and sign the learner out; the lock makes one tab refresh while the others pick up the new token through the storage event.

Test yourself

What does the client send at /authorize under PKCE S256?

  1. The code_verifier
  2. BASE64URL(SHA-256(code_verifier))
  3. The client secret
  4. The refresh token

Which ExcelTAD check defends against an authorization response from another server (mix-up)?

  1. exp
  2. Requiring iss in the response to equal the configured issuer
  3. The code length
  4. Web Locks

Why does ExcelTAD forbid third-party scripts on its main thread?

  1. Performance
  2. Its tokens live in localStorage, which any script in the origin could read
  3. CDNs are slow
  4. Browsers require it for PKCE

In the toy AS, the attacker had the code but not the verifier. What did the token endpoint return?

  1. tokens issued
  2. invalid_grant (PKCE verification failed)
  3. invalid_client
  4. A redirect