Skip to content

    Frontend System Design

    OAuth 2.0, OIDC and PKCE in Single-Page Apps

    Follow the OAuth 2.0 authorization code flow with PKCE and OpenID Connect from a single-page app's side: each parameter, each check and the attack it stops.

    By Published 22 min read

    • frontend-system-design
    • oauth
    • oidc
    • pkce
    • authentication
    Share

    Flagship lessonadvancedTypeScript labFrontend System Design

    Before this: Authentication vs Authorization in the UI

    What you'll learn: By the end of this lesson you will be able to name the four OAuth 2.0 roles and say why a single-page app is a public client, walk the authorization code flow with PKCE one request at a time, explain what state, nonce and the PKCE verifier each protect against, compute an S256 code challenge, validate an OpenID Connect ID Token the way the specification lists, explain why redirect URIs are matched as exact strings, compare three ways to keep tokens away from page script, and use a TypeScript model to watch each check reject its attack.

    Picture a cloakroom at a theatre. You hand over your coat and get a numbered ticket. Anyone holding the ticket can collect the coat, so a thief who snatches it from your pocket walks away well dressed. Now add a rule: when you hand the coat over, you also whisper a secret word that only you know, and the attendant writes down a scrambled form of it. To collect the coat you must hand over the ticket and say the word, and the attendant scrambles it the same way and compares. The ticket alone is worthless.

    That is the authorization code flow with PKCE. The ticket is the authorization code, the secret word is the code verifier, and the scrambled form is the code challenge. A single-page app (SPA) needs the rule because it runs in the user's browser, where nothing it holds can be kept secret from the person at the keyboard or from other software on the device.

    The running example is a staff dashboard at https://shop.example that lets people sign in through the company's identity provider at https://id.example. The .example names are reserved for documentation, and every token, code and lifetime in this lesson is a made-up demo value.

    The core idea

    Hold on to three statements.

    1. OAuth 2.0 delegates access; OpenID Connect (OIDC) adds who the user is. OAuth gives an app an access token for an API. OIDC is described by its specification as a simple identity layer on top of OAuth 2.0, and it adds the ID Token that tells the app who signed in.
    2. A browser app is a public client, so it must prove it is the app that started the flow. The authorization code travels through the browser's address bar, where it can be copied. PKCE binds the code to a secret the app kept, so a copied code is useless.
    3. Every value that comes back is checked before it is trusted. The callback is checked against state, the code is exchanged with a verifier, and the ID Token is checked for issuer, audience, expiry and nonce. Each check exists because a specific attack skips it.

    The lesson follows RFC 6749 (OAuth 2.0), RFC 7636 (PKCE), RFC 9700 (the security best current practice), RFC 10017 (OAuth 2.0 for Browser-Based Applications) and OpenID Connect Core 1.0. How the server side validates and issues is the subject of the paired back-end lesson. How the tokens are then stored is covered in a later lesson on token storage and secure cookies, and the difference between signing in and being allowed to do something is in the lesson on authentication versus authorization in the UI.

    The roles, and why a SPA is a public client

    RFC 6749 names four roles. The resource owner is the user. The resource server is the API that holds the data. The client is the app asking for access. The authorization server authenticates the user and issues tokens to the client. In this lesson id.example is the authorization server, the dashboard is the client and an API at https://api.shop.example is the resource server.

    The specification splits clients by whether they can keep credentials confidential. A confidential client can; a public client cannot. A server-side web app can hold a client secret in its own environment. A SPA's JavaScript, and everything it ships with, is delivered to the user, so RFC 10017 treats a browser app that runs the flow itself as a public client. That is why a secret baked into a SPA bundle protects nothing, and why the SPA needs another way to prove its identity.

    Two older approaches are gone from current advice. RFC 9700 says clients should not use the implicit grant (response type token, which returns the access token directly in the redirect) unless token injection is prevented and leakage is mitigated, and that the resource owner password credentials grant must not be used. RFC 10017 names several drawbacks of the implicit flow and says the current best practice for browser apps is the authorization code grant with PKCE.

    The flow, one request at a time

    Figure 1. Authorization code flow with PKCE

    sequenceDiagram accTitle: Authorization code flow with PKCE for a single-page app accDescr: The app creates a verifier, state and nonce, redirects the browser to the authorization endpoint with a challenge. The user signs in. The authorization server redirects back with a code and the state. The app checks the state and posts the code and verifier to the token endpoint, receives tokens, and checks the ID Token. participant App as SPA in the browser participant Id as Authorization server participant Api as API App->>App: create verifier, state, nonce
    challenge = S256(verifier) App->>Id: redirect: client_id, redirect_uri, scope,
    state, nonce, code_challenge Id->>Id: user signs in, grants access
    remembers the challenge with the code Id-->>App: redirect back: code, state App->>App: state matches the stored one? App->>Id: POST /token: code, code_verifier,
    redirect_uri, client_id Id->>Id: S256(verifier) equals stored challenge? Id-->>App: access token, ID Token, expires_in App->>App: check ID Token: iss, aud, exp, nonce App->>Api: request with the access token

    How to read this: the first half crosses the browser's address bar (the front channel), where anyone can read the code. The POST /token is a direct request from the app to the authorization server (the back channel), and it is the step that needs the verifier.

    Step by step:

    1. Prepare. The app generates three random values and keeps them where it can read them after the redirect: a code verifier, a state and a nonce.
    2. Authorization request. The app sends the browser to the authorization endpoint. The parameters are in the table below.
    3. Sign in. The user authenticates at the authorization server. The app never sees the password.
    4. Callback. The authorization server redirects to the registered redirect_uri with a code and the state.
    5. Token request. After checking state, the app sends the code and the verifier to the token endpoint.
    6. Tokens. The authorization server returns an access token, usually a refresh token, and (with OIDC) an ID Token. The app validates the response.
    Parameter Where Meaning
    response_type=code authorization request ask for an authorization code
    client_id both requests which registered app is asking
    redirect_uri both requests where to send the browser back; must be the same string in both
    scope authorization request what is requested; OIDC requires openid among them
    state request, echoed in callback opaque value that ties the callback to this attempt
    nonce request, returned inside the ID Token ties the ID Token to this attempt
    code_challenge, code_challenge_method authorization request the scrambled secret and how it was scrambled
    code_verifier token request the secret itself

    RFC 6749 recommends a maximum authorization code lifetime of 10 minutes and says the client must not use a code more than once. In the token request, redirect_uri must repeat the authorization request's value if it was sent there. RFC 7636 marks code_challenge required in the authorization request, code_challenge_method optional (defaulting to plain, which is why clients should always say S256) and code_verifier required in the token request. OpenID Connect Core says OIDC requests must contain the openid scope.

    Figure 2. Where each part lives and what crosses the browser

    The SPA, the authorization server and the API, and the two channels between themDashboard SPA to Authorize endpoint (redirect (front channel)); Authorize endpoint to Dashboard SPA (code + state); Dashboard SPA to Token endpoint (POST code + verifier); Token endpoint to Dashboard SPA (tokens); Dashboard SPA to Orders API (access token)AUTHORIZATION SERVERDashboard SPA: shop.exampleDashboard SPAshop.exampleAuthorize endpoint: id.exampleAuthorizeendpointid.exampleToken endpoint: id.exampleToken endpointid.exampleOrders API: api.shop.exampleOrders APIapi.shop.exampleredirect (front channel)code + statePOST code + verifiertokensaccess token

    How to read this: the dashed arrows are the redirects that pass through the address bar, visible to anything that can see the URL. The solid arrows are direct requests. Only the solid arrows carry the verifier or the tokens.

    Three checks that look alike and are not

    New readers often treat state, nonce and PKCE as three spellings of one idea. They guard different gaps, and RFC 9700 keeps them apart.

    Check Created by Compared where What it stops
    state the app, per attempt in the app, on the callback a callback the user did not start (cross-site request forgery against the redirect URI)
    PKCE verifier the app, per attempt at the authorization server, on the token request a stolen or injected authorization code
    nonce the app, per attempt in the app, inside the ID Token an ID Token replayed into a different login

    RFC 6749 says the client must implement CSRF protection for its redirection URI and should use state for it. RFC 9700 says clients must prevent CSRF and that a client that has confirmed the server supports PKCE may rely on PKCE for that protection, otherwise it needs state (or nonce in OpenID Connect). RFC 9700 also says nonce does not protect the authorization codes of public clients: for a SPA, PKCE is the defence against code injection. RFC 10017 says browser apps must prevent CSRF against their redirect URI, either with a unique state value or with PKCE. Sending all three costs a few lines, and the lab sends all three.

    PKCE in detail

    RFC 7636 describes the attack it answers: public clients are susceptible to the authorization code interception attack. A malicious app on the same device, or a script that can read the URL, copies the code from the redirect and redeems it before the real app does.

    The verifier. A high-entropy random string of the unreserved characters (letters, digits, -, ., _, ~), 43 to 128 characters long. RFC 7636 suggests at least 256 bits of entropy. 32 random bytes in base64url form give exactly 43 characters and 256 bits.

    The challenge. For the S256 method, code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))). The plain method sends the verifier itself as the challenge. RFC 7636 says clients that can must use S256, plain is for clients that technically cannot, and new implementations should not use it. RFC 9700 says the S256 method is the only one that does not expose the verifier in the authorization request.

    The check. The server stores the challenge with the code. At the token endpoint it transforms the presented verifier and compares. If they differ it must return invalid_grant. The attacker has the code and the challenge (both were in the redirect) but not the verifier, and the hash cannot be run backwards.

    Figure 3. A stolen code and a verifier the thief does not have

    sequenceDiagram accTitle: Authorization code interception stopped by PKCE accDescr: The honest app sends a challenge. The attacker copies the code from the redirect and posts it to the token endpoint without the verifier. The server computes the hash of what it receives, finds it differs from the stored challenge, and returns invalid_grant. The honest app then redeems the code with the real verifier. participant App as Honest SPA participant Id as Authorization server participant Bad as Attacker App->>Id: authorization request with code_challenge Id-->>App: redirect with code (the attacker can read it) Bad->>Id: POST /token: code (no verifier, or a guess) Id->>Id: S256(received) differs from stored challenge Id-->>Bad: invalid_grant App->>Id: POST /token: code + real verifier Id-->>App: tokens

    How to read this: the code is public once it is in a URL. The verifier never travels in a URL, and that is the entire defence.

    In a browser, the generator is a few lines of Web Crypto. The snippet below was run in Node 26, which has the same crypto global, and reproduced the RFC 7636 Appendix B example exactly; it was not run in a browser.

    function base64Url(bytes) {
      let binary = "";
      for (const byte of bytes) binary += String.fromCharCode(byte);
      return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
    }
    
    async function createPkcePair(bytes = crypto.getRandomValues(new Uint8Array(32))) {
      const verifier = base64Url(bytes);
      const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
      return { verifier, challenge: base64Url(new Uint8Array(digest)) };
    }

    MDN's page on Window.crypto covers getRandomValues(), the call used above for the random bytes. Never use Math.random() for a verifier, state or nonce: those values are secrets, and a predictable generator makes them guessable.

    What OpenID Connect adds

    OAuth alone tells the app that it may call an API. It does not say who the user is. OIDC adds the openid scope and an ID Token, a JWT that the authorization server issues to the app as a statement about the sign-in. The structure of a JWT and how its claims are validated is the subject of the next lesson. Here is what the ID Token is for, and the checks the specification lists for the authorization code flow.

    Claim Meaning
    iss who issued the token (the identity provider)
    sub who the user is, a locally unique identifier never reassigned within that issuer
    aud who the token is for; must contain your client_id
    exp the time on or after which the token must not be accepted
    iat when it was issued
    nonce the value you sent, if you sent one

    OpenID Connect Core 1.0 says the client must validate the signature (TLS validation of a direct token-endpoint response may stand in for the signature check), that iss exactly matches the issuer, that aud contains the client's client_id, that the current time is before exp, and that if a nonce was sent, a nonce claim is present and equals it. The iat claim can be used to reject tokens issued too far from now, with the limit left to the client. Two more facts matter for design: the only guaranteed unique identifier for a user is the pair iss and sub, so key your user records on both, and if you also call the UserInfo endpoint, its sub must exactly match the ID Token's.

    Figure 4. Validating the callback and the tokens, in order

    flowchart TD accTitle: Checks the SPA applies from callback to ID Token accDescr: First a login must be in progress and the stored state is spent. The callback must not be an error and the state must match. The iss parameter, if present, must be the expected issuer. The code is exchanged. The token response must be a bearer token with a sensible expiry. The ID Token must have the right issuer, audience, expiry and nonce. Any failure ends the login. A["Callback arrives"] --> B{"Login in progress?
    spend the stored state"} B -->|"no"| X["Reject"] B -->|"yes"| C{"error parameter?"} C -->|"yes"| X C -->|"no"| D{"state matches?"} D -->|"no"| X D -->|"yes"| E{"iss parameter, if present,
    is the expected issuer?"} E -->|"no"| X E -->|"yes"| F["Exchange code + verifier"] F --> G{"Response OK:
    bearer, expires_in, ID Token?"} G -->|"no"| X G -->|"yes"| H{"ID Token: iss, aud,
    exp, nonce correct?"} H -->|"no"| X H -->|"yes"| OK["Signed in"]

    How to read this: no code is sent anywhere until the state matches, and the stored state is deleted at the first step, so a callback URL cannot be processed twice.

    The ID Token is for the app; the access token is for the API. The audience differs for a reason: an API that accepts an ID Token as an access token can be called by anyone who can obtain an ID Token for any app of the same provider. Keep the roles apart and let the API check its own audience.

    Redirect URIs, and the mix-up attack

    The redirect URI is where the authorization server delivers the code. If an attacker can make the server deliver it to a URI they control, the code is theirs. RFC 9700 therefore says authorization servers must use exact string matching of the registered redirect URI (with an exception for the port of localhost in native apps). That is why https://shop.example/callback/ with a trailing slash is a different URI from https://shop.example/callback, and why a wildcard registration is the thing to avoid.

    A related attack applies to apps that work with several authorization servers. In a mix-up attack, the app is tricked into sending the code to the wrong server. RFC 9700 says such clients should use the iss parameter (defined in RFC 9207) as a countermeasure, and that the client must compare the received issuer to the one it stored. Our dashboard has one provider, and the lab still checks iss when it is present, because the check is cheap.

    RFC 9700 also says clients must not pass access tokens in a URI query parameter. Tokens belong in the Authorization header, never in a URL, where they are easy to copy into logs and history.

    Where the tokens end up

    After the callback, the SPA holds an access token and perhaps a refresh token. XSS is the reason this is the hard part: RFC 10017 says malicious script has the same privileges as the legitimate application code, so anything the app's JavaScript can read, injected script can read too.

    RFC 10017 lists three architecture patterns "in decreasing order of security":

    Pattern Who is the OAuth client Tokens in page JavaScript? Cost
    Backend for Frontend (BFF) the BFF, which must act as a confidential client none; the browser holds a session cookie a server component to run and a cookie session to defend
    Token-mediating backend the browser app, with a backend that handles token requests access token only, held briefly lighter than a BFF, weaker guarantees
    Browser-based OAuth client the browser app, a public client access and maybe refresh token no server of your own, the largest exposure to XSS

    The document says a BFF offers strong security guarantees and strongly recommends it for business and sensitive applications, because tokens are only available to the BFF, so none can be extracted from the browser. The lesson on the Backend for Frontend covers what the client asks of it, and the lesson on sharing authentication across micro-frontends places the same patterns in a shell. This lesson stays with the pure browser client because that is where PKCE matters most.

    For refresh tokens in browser apps, RFC 10017 says the refresh token is typically a bearer token, and authorization servers must either rotate refresh tokens on each use or use sender-constrained ones. RFC 9700 agrees for public clients and adds that with rotation, a replay of a spent token makes the server revoke the active one. The next lesson shows that behaviour in a model.

    Three illustrations

    Illustration 1 (minimal): the S256 transform

    The RFC 7636 Appendix B example, reproduced by the lab and by the snippet above: the 32 octets starting 116, 24, 223 encode to the verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk, and its S256 challenge is E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM. Anyone can compute the challenge from the verifier. Nobody can compute the verifier from the challenge.

    Illustration 2 (realistic): the staff dashboard signs in

    A staff dashboard is a SPA served from https://shop.example. The visitor clicks "Sign in", and the app stores a fresh state, nonce and verifier in sessionStorage (an illustrative choice: per tab, gone when the tab closes), then redirects. After sign-in the browser lands on https://shop.example/callback, a route that does nothing but run the checks in Figure 4, then moves the user to the page they asked for. The dashboard then calls the Orders API with the access token in an Authorization header. The app keeps the access token in memory, so a reload requires a silent re-authorization with a new verifier (the next lesson explains why that works while the identity provider's own session lasts).

    Illustration 3 (failure): the code that was copied, and the callback nobody asked for

    Two attacks at once. A malicious browser extension reads the callback URL and posts the code to the token endpoint. With PKCE the token endpoint answers invalid_grant. Meanwhile an attacker emails the user a link to https://shop.example/callback?code=...&state=... built from the attacker's own sign-in, hoping the dashboard will sign the user into the attacker's account. With a stored state the dashboard sees a different value, or none, and refuses before sending anything. Both defences are visible in the lab's output.

    Build it: watch each check stop its attack

    Goal. Run the whole flow against a model authorization server, then replay it with one thing wrong at a time: a stolen code, a callback nobody started, a replayed code, an unregistered redirect, a wrong nonce, a wrong audience.

    Setup. The lab is in the course's example workspace. It needs Node.js (captured on Node 26.13.1) and pnpm. It uses node:crypto only, with no network and a seeded random source, so every value it prints is a fake and the output is identical on every run.

    cd examples/frontend
    pnpm install
    pnpm --filter ./labs/oauth-pkce-model test   # 35 tests
    cd labs/oauth-pkce-model
    node src/demo.ts

    Steps.

    1. Read section 1 of the output. The verifier, its length and the S256 challenge match the RFC 7636 Appendix B example, and a test asserts the same.
    2. In section 3, follow the values: the challenge goes out in the authorization request, the code comes back with the state, and only the token request carries the verifier.
    3. In section 4, compare the two runs. With PKCE the attacker's request is refused, and the real client still succeeds. Without PKCE the attacker gets tokens and the real client then fails with code already used.
    4. In section 5, notice that the callback with another login's state sends zero token requests, and that opening the same genuine callback a second time is rejected because the stored state was spent.
    5. In section 7, read which stage rejects each ID Token: a wrong nonce, a wrong aud and an expired exp all fail after the exchange, and a forged iss parameter fails before it.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    === 1. The S256 transform, on the example in RFC 7636 Appendix B
    verifier:  dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk (43 characters)
    challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
    matches the RFC's challenge: true
    
    === 2. What counts as a valid verifier
    42 characters        -> too short (42 < 43)
    43 characters        -> valid
    128 characters       -> valid
    129 characters       -> too long (129 > 128)
    43 with a plus sign  -> contains a character outside the unreserved set
    43 with - . _ ~      -> valid
    
    === 3. The happy path: what travels where
    browser -> authorization endpoint (query):
      response_type=code
      client_id=shop-spa
      redirect_uri=https://shop.example/callback
      scope=openid profile
      code_challenge_method=S256
      state=ry6Mp5...  nonce=yYxrwi...  code_challenge=aHPY3C...
    authorization endpoint -> browser: https://shop.example/callback?code=kB8Cz-...&state=ry6Mp5...
    client -> token endpoint (body): grant_type=authorization_code code=kB8Cz-... code_verifier=Sj0QFp... (43 chars)
      server> authorize: code issued to shop-spa for user-1 (challenge S256, state echoed)
      server> token: tokens issued to shop-spa (PKCE verified)
    client result: accepted
    session: sub=user-1, access token valid until t=1300 (now t=1000)
    
    === 4. A stolen code: with PKCE and without
    -- server requires PKCE: true
      attacker, no verifier:    refused (invalid_grant: code_verifier missing)
      attacker, guessed verifier: refused (invalid_grant: code_verifier does not match the code_challenge)
      the real client then:     accepted
    -- server requires PKCE: false
      attacker, no verifier:    TOKENS ISSUED to the attacker
      the real client then:     rejected at token: invalid_grant: code already used
    
    === 5. State and the callback URL
    callback with no login in progress: rejected at callback: no login in progress (state cannot be checked)
    callback carrying another login's state: rejected at callback: state does not match
    token requests sent so far: 0
    genuine callback: accepted
    the same callback opened again: rejected at callback: no login in progress (state cannot be checked)
    (first state was ry6Mp5..., spent when its callback arrived)
    
    === 6. Redirect URIs, code lifetime and replay
    redirect_uri https://shop.example/callback                -> code issued
    redirect_uri https://shop.example/callback/               -> refused, shown to the user
    redirect_uri https://shop.example/callback?next=/admin    -> refused, shown to the user
    redirect_uri https://evil.example/callback                -> refused, shown to the user
    redeemed 61 s after issue (code lifetime 60 s, illustrative): rejected at token: invalid_grant: code expired
    first redemption: accepted; replay of the same code with the right verifier: refused (code already used)
    
    === 7. The ID Token claims, and the issuer parameter
    claims as issued                 -> accepted
    nonce from another login         -> rejected at id-token: nonce does not match
    aud is another app               -> rejected at id-token: aud does not contain shop-spa
    aud array containing this app    -> accepted
    iss is another issuer            -> rejected at id-token: iss https://other.example does not match the issuer
    exp already passed               -> rejected at id-token: ID Token expired
    iat 900 s ago                    -> rejected at id-token: ID Token issued more than 600 s ago
    callback iss=https://id.example -> accepted
    callback iss=https://evil-idp.example -> rejected at callback: iss https://evil-idp.example is not the issuer this login started with (token requests sent: 0)

    What the lab does not show. No real identity provider or browser is involved, the ID Token has no signature (the next lesson's lab verifies real signatures), "random" values come from a seeded hash, and the lifetimes (a 60-second code, 600-second maximum ID Token age) are illustrative policy choices of the lab. A code is burned only when a token request succeeds, which is a lab choice: a server may instead burn it at the first attempt.

    Break it. In src/authServer.ts, in token, change if (!verifierMatches(record.challenge, record.method, verifier)) { to if (false) {. The server no longer compares the verifier with the challenge, tests about the attacker fail, and section 4 of the demo shows tokens issued to a guessed verifier. Revert it.

    Stretch. Pick one:

    • Make the server burn a code on the first attempt that finds it, and decide which lesson sentence and which tests change.
    • Add a second authorization server to the world and write the mix-up attack as a test.
    • Add a client option for the plain method and show why a server should refuse it by default.

    Choosing

    Figure 5. Which sign-in architecture for which app

    flowchart TD accTitle: Choosing where OAuth runs for a browser app accDescr: If the app is sensitive or has a server component available, use a backend for frontend that holds the tokens. If it needs tokens in the browser but can run a small backend, use a token-mediating backend. Otherwise run the authorization code flow with PKCE as a public client and plan for XSS. Q1{"Can you run a server
    component for this app?"} -->|"yes"| Q2{"Sensitive data
    or business app?"} Q1 -->|"no"| P["Browser-based OAuth client:
    code + PKCE, rotating refresh,
    strong XSS defences"] Q2 -->|"yes"| B["BFF: tokens stay
    on the server"] Q2 -->|"no"| M["Token-mediating backend
    or BFF"]

    How to read this: the question is not "which library" but "where can a token be kept". If the answer is "only in the browser", the XSS defences in the following lessons carry the weight.

    Choice Gain Cost
    Code + PKCE, public client no server to run; standard flow tokens in page memory or storage; XSS exposure
    Add state and nonce as well each closes its own gap; cheap a few lines and stored values per attempt
    BFF no token in page JavaScript a server, a session, CSRF defences
    Rotating refresh tokens a stolen refresh token is detected on reuse the client must serialize refresh calls
    Exact redirect URI no code delivered elsewhere one registration per environment and preview

    The other side of this topic

    On the back end the same flow is written from the other seat: registering clients and exact redirect URIs, requiring PKCE, issuing and expiring codes, signing tokens, and publishing the keys that resource servers use. The paired back-end lesson covers that half. The front-end skill is knowing what to store, what to compare and what to refuse.

    In practice: adding company sign-in to a staff dashboard

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A staff dashboard has its own username and password form. The company is moving to a single identity provider, and security requires that the dashboard stop handling passwords. The dashboard is a SPA with a small REST API behind it. Three engineers own it, and it ships to staging and production plus a preview environment per pull request.

    Starting architecture

    Figure 6. Starting point: the SPA handles passwords itself

    Starting architecture: the dashboard collects the password and holds a long-lived session tokenLogin form to Dashboard API (password); Dashboard API to User table (verify)Login form: in the SPALogin formin the SPADashboard API: checks the passwordDashboard APIchecks thepasswordUser table: password hashesUser tablepassword hashespasswordverify

    How to read this: the password crosses the app and the API, and the app owns a user table. The goal is to remove both.

    Options considered

    Option What it fixes What it costs Risk
    Authorization code + PKCE in the SPA no passwords in the app; standard flow SPA holds the tokens XSS exposes them
    BFF in front of the API tokens never reach JavaScript a new service and cookie session more to run for three engineers
    Keep the password form, add 2FA smallest change the app still handles passwords does not meet the requirement

    The decision

    Field Decision record
    Context The dashboard must stop handling passwords, ships to several environments, and holds only internal data of moderate sensitivity.
    Decision Use code + PKCE (S256) with state and nonce, exact redirect URIs per environment, access token in memory, rotating refresh tokens. Revisit a BFF when the dashboard gets more sensitive data.
    Consequences, good No passwords in the app, standard flow, no new service.
    Consequences, bad Tokens live in the page, so XSS has a bigger payoff; each preview environment needs a registered redirect URI.
    Revisit when The dashboard shows data the company classes as sensitive, or an XSS finding raises the cost of exposure. Then move to a BFF.

    Rollout and verification

    1. Register one redirect URI per environment and test each, including the trailing-slash variant, which must fail.
    2. Test the failure paths in staging: a tampered state, an expired code, an ID Token for another client, the callback opened twice.
    3. Check the callback route does exactly one thing: it runs the checks, clears the stored values and navigates away.
    4. Watch the token endpoint's error rate by error code after launch.

    The 2 a.m. failure

    Soon after release, support reports that some staff are "stuck in a sign-in loop". The identity provider's logs show pairs of token requests carrying the same authorization code a few milliseconds apart: the first succeeds and the second fails with invalid_grant.

    The cause is in the callback route. A refactor moved the code exchange into an effect that runs more than once for one page load (for example, because the component is mounted twice). The first run signs the user in, the second fails, and the error handler clears the session and restarts the login. This is exactly the case the lab covers: a code is single use, so one callback must be processed once.

    First three checks: (1) look at the token endpoint logs for duplicate codes; (2) read the callback route for anything that can run twice; (3) confirm what the app does on a second, failing exchange. Mitigation: put a "callback handled" guard in front of the exchange and make a missing stored state a no-op when the user is already signed in. Follow-up: delete the stored state and verifier at the start of handling, as the lab's client does, add a test that calls the handler twice, and alert on a rise in invalid_grant.

    Architect's notes

    • Make the callback route boring. One module, one job: check, exchange, validate, clear, navigate. No UI work in it.
    • Always send S256, state and nonce, even when one of them seems redundant for your flow. The cost is small and the three guard different gaps.
    • Register exact redirect URIs per environment and treat a wildcard request from a team as a design question to answer.
    • Decide early where tokens will live. If the answer is "in the browser", plan XSS defences, short access-token lifetimes and rotating refresh tokens as part of sign-in, not afterwards.
    • Key user records on iss and sub, not on email.

    Common mistakes

    • Putting a client secret in the SPA bundle. It is public the moment it ships.
    • Using the implicit grant, or the password grant, because an old tutorial did.
    • Omitting code_challenge_method. It defaults to plain.
    • Using Math.random() for the verifier, state or nonce.
    • Checking state after the code exchange instead of before it.
    • Accepting any aud. An ID Token for another app is not yours.
    • Treating an ID Token as an access token for the API.
    • Registering a wildcard redirect URI or ignoring a trailing slash.
    • Processing the callback twice, which fails on the single-use code and often restarts the login.

    Key takeaways

    • OAuth 2.0 delegates access; OIDC adds the ID Token that says who signed in. A SPA is a public client.
    • The authorization code flow with PKCE is the standard flow for browser apps. RFC 9700 says public clients must use PKCE and that the implicit grant should not be used.
    • The verifier is 43 to 128 unreserved characters from a strong random source. The challenge is BASE64URL(SHA256(verifier)). A stolen code without the verifier gets invalid_grant.
    • state ties the callback to the attempt, the verifier ties the code to the app, and the nonce ties the ID Token to the attempt.
    • Validate the ID Token: iss, aud containing your client_id, exp, nonce, and the signature. Identify users by iss plus sub.
    • Redirect URIs are compared as exact strings. Access tokens never go in a URL query.
    • RFC 10017 ranks BFF above token-mediating backend above browser-based client by security. Refresh tokens for browser apps are rotated or sender-constrained.
    • A code is single use: process each callback once, and spend the stored state first.

    Practice exercises

    Exercise 1 — Starter (30 min): Run the demo, and for each scenario in sections 4 to 7 write down which check rejected it and what the attacker would have needed to get past it.

    Exercise 2 — Intermediate (2 hours): Add a test to the lab where the token endpoint returns an ID Token whose aud is an array containing "another-app" only, and one where aud contains both. Then add the OpenID Connect azp rule and decide which of your tests change.

    Exercise 3 — Intermediate (2 hours): Write the callback route of a small SPA with the handled-once guard from the 2 a.m. section. Write the two tests that matter: calling the handler twice, and calling it with no stored state while already signed in.

    Exercise 4 — Advanced (half day): Write a design note for a SPA that must show payroll data: choose between a pure browser client and a BFF, list what an XSS bug would expose in each, and say what you would measure after launch.

    In this course:

    Elsewhere on the site:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments