Skip to content

    Frontend System Design

    Authentication Flows From the SPA to the API

    Follow sign-in from the browser to the API: password, passkey, session cookie, bearer token, SSO redirect, silent refresh, logout and 401 handling.

    By Published 14 min read

    • frontend-system-design
    • authentication
    • sessions
    • sso
    • passkeys
    Share

    Standard lessonintermediateFrontend System Design

    Before this: Token Storage and Secure Cookies

    What you'll learn: By the end of this lesson you will be able to describe the loop every sign-in flow follows (prove who you are, receive a credential, present it, end it), trace a password, passkey, session-cookie, bearer-token and SSO redirect flow from the browser to the API, decide what a single-page app should track about the signed-in state, handle 401 and 403 responses in one place without loops, and explain what logging out has to do on the server and in other tabs.

    Think of an airport. At check-in you prove who you are and receive a boarding pass. At each gate an agent scans the pass and either lets you through or sends you back to a desk. If you lose the pass, you report it so the airline can cancel it, because tearing up your own copy does not stop someone who photographed it. Authentication on the web has the same shape: a desk, a pass, many scans, and a way to cancel.

    The running example is the orders area of the shop at https://shop.example, a single-page app that calls an API. For the SSO sections an identity provider lives at https://id.example. (Reserved .example names, and no real credentials, appear in this lesson.) Where the credential should be stored is the subject of Token Storage and Secure Cookies, so this lesson links to it instead of repeating it. Authorization, meaning what a signed-in user may do, is a separate lesson and appears here only as the difference between 401 and 403.

    The core idea

    1. Every flow is the same four steps. Prove who you are, receive a credential, present it on later requests, end it. Flows differ in who does each step: the page, a backend, an identity provider, or the browser's own cookie machinery.
    2. The front end's job is state and navigation, not cryptography. It shows the right screen, sends the credential the right way, and reacts when the credential stops working. The checks that matter happen on the server.
    3. Every flow ends with the same question: what happens when the credential stops working? Answer it once, in one place, or each screen answers it differently.

    The actors and the loop

    Figure 1. The actors in a sign-in

    The browser app, a backend, an identity provider and the API in one sign-in loopUser to Browser app (proves who they are); Browser app to Backend (sign in, session check); Browser app to Identity provider (redirect (SSO)); Backend to Identity provider (code exchange); Backend to API (credential)YOUR SYSTEMUser: password or passkeyUserpassword orpasskeyBrowser app: shop.exampleBrowser appshop.exampleBackend: sessions or tokensBackendsessions ortokensIdentity provider: optionalIdentityprovideroptionalAPI: checks the credentialAPIchecks thecredentialproves who they aresign in, session checkredirect (SSO)code exchangecredential

    How to read this: the identity provider is optional. Without it, the backend checks the user itself. With it, the page sends the user to the provider, and the backend receives the result. Either way the API only ever sees a credential, and the page only ever sees a response.

    Step one: proving who you are

    Passwords

    In the simplest flow the page shows a form, posts the typed credentials to a sign-in endpoint over HTTPS, and discards them. The response is the credential from step two: a Set-Cookie header, or a token in the body. The page should hold the typed password only in the input and never write it to storage or logs. Everything else about passwords (hashing, rate limiting, breach checks) is server-side work and out of scope here.

    Passkeys

    MDN's Web Authentication API page and its passkeys guide describe a passkey as a public and private key pair bound to a specific user's account on a particular website, so nothing shared is sent. The private key stays in an authenticator (built into the device or a removable key), and the website's server stores the public key. In both registration and sign-in the server issues a random challenge, the page calls navigator.credentials.create() (registration) or navigator.credentials.get() (sign-in) with the publicKey option, and the signed result goes back to the server to verify. MDN notes the challenge must be at least 16 bytes of random data, and that WebAuthn is available only in secure contexts (HTTPS).

    Figure 2. Passkey sign-in

    sequenceDiagram accTitle: Signing in with a passkey accDescr: The page asks the server for a challenge. The server returns a random challenge. The page calls navigator.credentials.get with that challenge. The authenticator asks the user to approve, then signs the challenge together with the origin. The page sends the signed assertion to the server. The server verifies it with the stored public key, checks the origin is the expected one, and starts a session. participant P as Page participant A as Authenticator participant S as Server P->>S: request a sign-in challenge S-->>P: random challenge P->>A: credentials.get with the challenge A->>A: user approves, key signs challenge and origin A-->>P: signed assertion P->>S: send the assertion S->>S: verify with the stored public key, check the origin S-->>P: session started (cookie or token)

    How to read this: the page relays messages between the server and the authenticator. It never sees a private key or a password, so there is nothing for a phishing page to collect.

    MDN gives the reason for the phishing resistance: by default a passkey can only be used by a page from the same origin (excluding the port) as the page that created it, and the signed assertion includes the caller's origin, which the server must check against what it expects. MDN also notes passkeys do not remove every threat: attacks may target user devices or account recovery. A passkey proves identity; the session or token it leads to still has to be stored and ended carefully, as the rest of this lesson describes.

    Federated sign-in (SSO)

    Instead of checking the user itself, the app sends them to an identity provider and receives the result afterwards. That flow is the next-but-one section; the credentials the user types never pass through your page at all.

    In the cookie flow the browser holds an opaque session identifier and attaches it itself.

    Figure 3. Cookie session from sign-in to API call

    sequenceDiagram accTitle: Session cookie flow accDescr: On start the app asks the backend whether a session exists and is told no. The user submits credentials. The backend verifies them, creates a session and answers with a Set-Cookie header. Later calls from the app carry the cookie automatically. When the session ends the backend answers 401 and the app returns to the sign-in screen. participant U as User participant P as Page participant B as Backend P->>B: GET /session (page start) B-->>P: 401, no session U->>P: submits credentials P->>B: POST /sign-in B->>B: verify, create a new session identifier B-->>P: 200 with a Set-Cookie header P->>B: GET /api/orders (cookie attached by the browser) B-->>P: 200 orders Note over P,B: later, the session expires on the server P->>B: GET /api/orders B-->>P: 401 P->>P: show the sign-in screen

    How to read this: the page's only jobs are the start-up check, the sign-in call and reacting to 401. It never touches the credential.

    Four points matter for client code.

    • The page asks the server who it is. A start-up check such as GET /session tells the app whether to show the signed-in or signed-out screen. The page should not guess from local data.
    • Same-origin calls send cookies by default. MDN says fetch credentials default to same-origin: cookies go with same-origin requests only. For a cross-origin API the request must use credentials: "include" and the server must allow it through CORS headers, as CORS in Practice explains. Putting the backend on the page's origin avoids the whole topic.
    • The identifier changes at sign-in. OWASP says the session ID must be renewed or regenerated after any privilege level change. That is a server duty, but the front end should expect a new Set-Cookie in the sign-in response and never carry an identifier across.
    • Cookies bring CSRF. Because the browser attaches the cookie, the backend needs a defence against cross-site requests; Token Storage and Secure Cookies covers the attributes and why.

    Steps two and three: a bearer token

    In the token flow the page receives a token and attaches it to each call. RFC 6750 specifies sending it in the Authorization request header with the Bearer scheme and says tokens should be short-lived (one hour or less), with browser-based clients named as a reason.

    // Illustrative sketch, not a library: the page attaches the token, and any 401 goes to one place.
    export async function apiFetch(path: string, getToken: () => string | undefined, onUnauthorized: () => void): Promise<Response> {
      const token = getToken();
      const headers = new Headers();
      if (token) headers.set("Authorization", `Bearer ${token}`);
      const res = await fetch(path, { headers });
      if (res.status === 401) onUnauthorized(); // refresh once, or go to sign-in
      return res;
    }

    Short lifetimes mean the token will expire during a visit, so the app needs a refresh path: either a backend that swaps a cookie for a new access token, or a refresh token used by the page. Where each lives is the storage question again. The OAuth browser-based apps document (RFC 10017) names three architectures that differ here, and warns that the pattern where the page itself holds all the tokens is vulnerable to every attack scenario it lists.

    Session cookie flow Bearer token flow
    What the page holds Nothing it can read A short-lived access token, usually in memory
    Who attaches the credential The browser, automatically Your code, on each call
    On reload Still signed in Needs a silent refresh
    Main extra risk CSRF, handled by the backend Token readable by script, and refresh complexity
    Cross-origin APIs Need credentials: "include" and CORS Work with a header, no cookies involved

    The SSO redirect

    Single sign-on moves step one to an identity provider. Sign-in is a navigation, not a fetch: the browser must follow redirects to the provider and back so the user can see its page. RFC 10017 requires the page, when it is the OAuth client, to use the authorization code flow with PKCE, and has a backend act as a confidential client in the other patterns.

    Figure 4. Redirect sign-in at a high level

    sequenceDiagram accTitle: SSO redirect sign-in accDescr: The user clicks sign in. The app navigates the browser to the identity provider. The user authenticates there. The provider redirects the browser back to the app's callback address with a one-time code. The callback request reaches the backend, which exchanges the code for tokens and starts a session. The browser lands on the page the user first wanted. participant U as User in browser participant A as App and backend participant I as Identity provider U->>A: click sign in (remember the page they wanted) A-->>U: redirect to the identity provider U->>I: authenticate I-->>U: redirect back to the callback with a code U->>A: callback request carries the code A->>I: exchange the code (and the PKCE verifier) I-->>A: tokens A-->>U: start a session, redirect to the remembered page

    How to read this: the page's code runs before the first arrow and after the last. In between, the browser is on other pages. The callback arrives as a top-level navigation from another site, and that detail matters for cookies.

    Two front-end details are easy to miss. First, the return address: the app must remember where the user was heading, and when it redirects there afterwards it should accept only paths on its own site, never an arbitrary URL from a query string (design guidance, not from a source here). Second, the callback is a cross-site top-level navigation. Under MDN's SameSite rules a Strict cookie is not sent on it, while a Lax cookie is sent on a top-level GET. Any short-lived cookie the app set before redirecting, such as one holding the flow's state, must be readable at the callback. The failure below comes from getting that wrong.

    What the page should track

    A client needs a small model of the sign-in state, and the same four states appear in most apps.

    Figure 5. Sign-in states in the client

    stateDiagram-v2 accTitle: Client-side sign-in states accDescr: The app starts in unknown and checks the session. The check ends in signed in or signed out. A signed-in app that receives a 401 tries one refresh. If the refresh works it stays signed in. If it fails the app is signed out. Signing out also leads to signed out. [*] --> unknown unknown --> checking: page start checking --> signedIn: session found checking --> signedOut: no session signedIn --> refreshing: 401 refreshing --> signedIn: refresh worked refreshing --> signedOut: refresh failed signedIn --> signedOut: sign out signedOut --> checking: sign in finished

    How to read this: the page renders a neutral state while it is unknown or checking, instead of flashing the signed-out screen to someone who is signed in.

    Treat "signed in" in the client as a hint for what to show, not as permission. Hiding a button does not stop a request, and the server decides every call. Keep tokens out of this state object if possible, since state is often logged or persisted by libraries (see State Persistence and Synchronization).

    Handling 401 and 403 in one place

    MDN defines 401 as a request that lacks valid authentication credentials, sent with a WWW-Authenticate header naming the scheme the server expects. 403 is returned when the request has valid credentials but the client lacks permission, and for it "authenticating or re-authenticating makes no difference". Servers may also answer 404 to hide that a resource exists. The distinction decides what the client does.

    Figure 6. What to do with an error response

    flowchart TD accTitle: Handling authentication errors in a request wrapper accDescr: A request gets a response. A 401 on a first attempt triggers one refresh or session check then one retry. A second 401 sends the user to sign in. A 403 shows a not-allowed message and does not retry. Other errors follow the normal error handling. R["Response"] --> Q{"Status"} Q -->|"2xx"| OK["Use it"] Q -->|"401"| T{"Already retried
    once?"} T -->|"no"| F["Refresh or re-check session,
    retry once"] T -->|"yes"| S["Go to sign-in,
    remember the page"] Q -->|"403"| D["Show 'not allowed',
    do not retry"] Q -->|"other"| E["Normal error handling"]

    How to read this: the retry count is what prevents a loop. Re-authenticating cannot fix a 403, so retrying it only repeats the failure.

    When several requests get 401 at once, one refresh should serve them all (a "single flight") instead of each starting its own, and requests that arrive during the refresh should wait for it. Request Cancellation, Retries and Timeouts and Client Retries and Backoff cover the retry mechanics. An outage or a 500 is not an authentication failure and must not send the user to sign in.

    Logging out

    Signing out has three parts. End the session on the server: OWASP says the application "must invalidate the session at least on server side", and deleting a cookie in the browser does not stop a copy someone else holds. Clean the browser: the response can delete the cookie, and MDN's Clear-Site-Data header can clear cached data, cookies and DOM storage for the site. Tell the other tabs: a sign-out in one tab should reach the others, for example through a BroadcastChannel message; Cross-Tab Sync With BroadcastChannel shows the pattern. Whether signing out of your app also ends the identity provider's session is a separate product decision.

    Choice Gain Cost
    Session cookie flow Nothing for script to steal, simple client Backend session store, CSRF defence
    Bearer token flow Works across origins, easy to attach Refresh logic, token exposed to script
    Passkeys No shared secret to phish Registration and recovery flows to design
    SSO redirect No credentials in your page, one login for many apps Redirect plumbing, callback and state handling

    In practice: adding SSO to an orders app

    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

    The orders app at https://shop.example has its own password form and a session cookie. A parent company wants every internal app behind one identity provider at https://id.example. The team adds a redirect sign-in. Four engineers own the app.

    Starting architecture

    Figure 7. Before and during the change

    Redirect sign-in: the browser leaves the app, signs in at the provider and returns to a callbackOrders app to Identity provider (redirect); Identity provider to Backend (callback with code); Backend to Orders app (session cookie)SHOP.EXAMPLEOrders app: shop.exampleOrders appshop.exampleBackend: callback, sessionBackendcallback, sessionIdentity provider: id.exampleIdentityproviderid.exampleredirectcallback with codesession cookie

    How to read this: the callback is a request from the provider's site to the app, so it is cross-site.

    Options considered

    Option What it fixes What it costs Risk
    Keep the password form, add a link to SSO Both paths work during rollout Two flows to maintain Users pick the wrong one
    Replace the form with redirect sign-in One flow, one place for policy Callback and state handling Cookie and redirect mistakes lock users out
    Page-side token flow against the provider No backend change The page holds tokens Larger script exposure

    The decision

    Field Decision record
    Context An internal app must use a shared identity provider.
    Decision Redirect sign-in handled by the backend, which exchanges the code and sets the session cookie. The page only navigates, checks GET /session and handles 401.
    Consequences, good No credentials or tokens in the page, one place to end sessions.
    Consequences, bad Callback and state handling to get right, plus a login-state cookie to design.
    Revisit when More apps share the provider (consider a shared sign-in service) or session lifetime needs change.

    Rollout and verification

    1. Dual-run the password form and redirect for one team, behind a flag.
    2. Test the callback from a clean browser profile and from a link opened in another site, and check which cookies each request carries.
    3. Check logout in two tabs and confirm the server session is gone.
    4. Remove the password form only after the callback error rate is quiet for a week.

    The 2 a.m. failure

    After the rollout, some users bounce between the app and the provider and see "state mismatch" errors. The backend stores a random state value in a short-lived cookie before it redirects, and compares it at the callback. That cookie was set with SameSite=Strict. The callback is a cross-site top-level navigation, so a Strict cookie is not sent, the comparison fails, and the app starts the flow again.

    First three checks: (1) look at the callback request in the network panel and see whether the state cookie is in its Cookie header; (2) compare the cookie's SameSite value; (3) check whether users who opened the app from a bookmark behave differently. Mitigation: set the short-lived state cookie to SameSite=Lax, which a top-level GET carries. Follow-up: add a test that issues the callback as a cross-site navigation, and write down why the session cookie and the state cookie have different attributes.

    Architect's notes

    • Make the start-up session check the single source of truth for the signed-in screen, and render a neutral state until it answers.
    • Put every 401 in one wrapper with a retry limit and a single-flight refresh.
    • Keep sign-in a navigation for SSO, and validate the return address.
    • Treat client state as a hint, because the server decides each request.
    • Test logout in two tabs and test the callback from another site.

    Common mistakes

    • Retrying 403, or looping on 401 with no retry limit.
    • Flashing the signed-out screen before the session check returns.
    • Redirecting to any URL a query string supplies after sign-in.
    • A Strict cookie that must survive a cross-site redirect.
    • Treating logout as deleting a cookie, or as one tab's concern.
    • Sending users to sign in because of a network error or 500.

    Key takeaways

    • Every flow follows four steps: prove, receive, present, end.
    • A passkey proves identity with a signed challenge bound to the origin; no shared secret is sent.
    • A cookie flow lets the browser attach the credential; a token flow has your code attach it and needs a refresh path.
    • SSO is a navigation to the provider and back, and the callback is cross-site.
    • Track unknown, checking, signedIn and signedOut, and treat them as hints.
    • 401 means credentials are missing or invalid, 403 means they are valid but not enough. Retry the first once, never the second.
    • Logout is a server action, plus cleanup and a message to the other tabs.

    Practice exercises

    Exercise 1 — Starter (30 min): Draw your app's sign-in as the four steps. For each step write who does it and what the page holds afterwards.

    Exercise 2 — Intermediate (2 hours): Write a request wrapper that handles 401 with a single-flight refresh and one retry, treats 403 as final, and ignores network errors. Test the case where five requests fail at once.

    Exercise 3 — Advanced (half day): Design the callback and the state cookie for a redirect sign-in. List the cookie attributes and justify each against the cross-site callback. Mark every claim you could not check against a source.

    In this course:

    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