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
401and403responses 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
- 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.
- 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.
- 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
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
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.
Steps two and three: a session cookie
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
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 /sessiontells 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
fetchcredentials default tosame-origin: cookies go with same-origin requests only. For a cross-origin API the request must usecredentials: "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-Cookiein 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
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
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
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
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
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
- Dual-run the password form and redirect for one team, behind a flag.
- Test the callback from a clean browser profile and from a link opened in another site, and check which cookies each request carries.
- Check logout in two tabs and confirm the server session is gone.
- 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
401in 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 on401with 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
Strictcookie 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,signedInandsignedOut, and treat them as hints. 401means credentials are missing or invalid,403means 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.
Related reading
In this course:
- Token Storage and Secure Cookies, where the credential lives and how cookie attributes behave.
- The Backend for Frontend (BFF) from the Client's Side, the cookie-session pattern.
- CORS in Practice, cookies on cross-origin requests.
- Sharing Authentication Across Micro-Frontends, one sign-in for several fragments.
- State Persistence and Synchronization and Cross-Tab Sync With BroadcastChannel, keeping tabs in step.
Official documentation
- MDN: Passkeys, how they work and why they resist phishing.
- IETF: OAuth 2.0 for Browser-Based Applications, the architectures and the code flow with PKCE.
- RFC 6750: Bearer Token Usage, the
Authorizationheader and token lifetime. - MDN: 401 Unauthorized, with the 403 page linked above.
- OWASP: Session Management Cheat Sheet, regeneration and server-side invalidation.
- MDN: Request.credentials, when
fetchsends cookies.