Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 132 ยท Routing and Apps

Authentication and Authorization Patterns

Build sign-in flows in React - sessions versus tokens, an auth context, protected routes, role-based UI, token refresh, the OAuth redirect flow, and why you must never trust the client.

Almost every real app has a "who are you?" question and a "what are you allowed to do?" question. The first is authentication (proving identity, usually by signing in). The second is authorization (checking permissions: may this user edit this invoice?). React helps you build the screens for both, but React runs in the visitor's browser, and the visitor controls the browser. That one fact shapes every pattern in this lesson.

You will learn the two ways a server remembers a signed-in user (sessions and tokens), how to share the current user through context, how to protect routes, how to show or hide parts of the UI by role, how token refresh works, and how an OAuth "Sign in with..." redirect flow is put together. All demos use a fake in-page server, because the editor has no real network and you should never type real passwords into a demo anyway.

Never implement password hashing, token signing or session storage in the browser, and never treat a hidden button as security. Real authentication is done by your server (or a dedicated service such as Auth.js, Clerk, Auth0, Supabase or Firebase Auth). The React code only reflects the result.

Authentication versus authorization

Authentication Authorization
Question Who are you? What may you do?
Happens At sign-in, and when a session or token is verified On every protected action
Example failure 401 Unauthorized ("not signed in") 403 Forbidden ("signed in, but not allowed")
In React Login form, auth context, redirect to sign-in Hiding buttons, disabling routes by role
Who enforces it The server The server (React only improves the experience)

Keep the last row in mind. The UI hides the "Delete user" button from members because showing a button that always fails is bad design, not because hiding it is secure. The server must refuse the request anyway.

Sessions versus tokens

After a successful sign-in the server must recognize the same user on the next request. There are two common designs.

Session cookie. The server creates a session record and sends its id in a cookie marked HttpOnly (JavaScript cannot read it), Secure (HTTPS only) and SameSite=Lax or Strict (limits cross-site sending). The browser attaches the cookie automatically. Your React code never sees the credential:

JavaScript
// Read-only sketch: needs a real server that sets the cookie
const response = await fetch('/api/me', { credentials: 'include' });
if (response.status === 401) {
  // not signed in
}

Token (for example a JWT). The server returns a signed token and the client sends it in an Authorization: Bearer <token> header. Tokens suit mobile apps and APIs used by many clients, but now your JavaScript must hold the token, and that is the risky part. If you keep it in localStorage, any script that runs on your page (a compromised dependency, an XSS bug) can steal it. A common compromise is a short-lived access token kept only in memory plus a long-lived refresh token in an HttpOnly cookie.

For a browser app that talks to its own backend, a plain HttpOnly session cookie is usually the simplest and safest choice. Cookies bring one new risk, CSRF (another site making your browser send an authenticated request), which SameSite cookies and CSRF tokens address. Frameworks and auth libraries handle this for you; know that the risk exists.

An auth context

Many components need to know the current user: the header, the account page, route guards. That is a classic job for context. The pattern below uses a status that has three values, not two. Why three? Because when the page first loads you do not yet know whether the user is signed in (the check is asynchronous). Treating "unknown" as "signed out" causes a flash of the login page for signed-in users.

AuthProvider with a fake server

Try a wrong password first, then secret1. Three details are worth copying:

  • useAuth throws a clear error if used outside the provider, which catches wiring mistakes immediately.
  • The form disables the button while the request runs, so a double click cannot send two sign-ins.
  • Errors are shown with role="alert" so screen readers announce them. Say "wrong email or password", never "no such email": telling attackers which emails exist helps them.

In a real app the provider would also check for an existing session on mount (GET /api/me) and start in a loading status until that finishes. Only the guard components, covered next, need to care about the difference.

Protected routes

A protected route is a page that signed-out visitors cannot see. The usual pattern is a wrapper component: if the user is signed in, render the children; if not, redirect to the sign-in page and remember where they wanted to go, so you can send them back afterwards. Our editor runs in a sandbox where the History API is unavailable, so this demo uses the URL hash (#/account) as a mini router. The same guard works unchanged with React Router; see Client-Side Routing.

RequireAuth guard with hash routing

Click Account (private) while signed out: the guard redirects to /login?return=%2Faccount, the login page shows where you will land, and signing in sends you to the account page. Notice the open redirect check (safe): the return value comes from the URL, which anyone can craft. If you blindly navigated to //evil.example, a phishing link could bounce users to another site right after login. Only accept paths that start with a single /. This site's own login does the same.

Two more guard notes:

  • When your auth status can be loading, the guard must render a spinner (not redirect) until it is known.
  • A guard protects the screen, not the data. The API behind the screen still has to refuse unauthenticated requests, because anyone can call it without your React code.

Role-based UI, and why the client is not the boundary

Authorization in the UI usually means a Can helper that shows or hides parts based on the user's role or permissions. The server returns permissions (['users:delete']) or a role, and the UI checks them. Compare the two approaches in this demo. Switch to the member and try the "hacked client" button, which sends the request even though the UI hides the real one.

Hiding is not security

As Bob, the real delete button is hidden, but the tampered request still reaches the server, which answers 403 - Forbidden: admins only. That is the correct design: UI checks are for usability, server checks are for security. A visitor can open DevTools, change JavaScript variables, edit your bundle or skip your app entirely and send requests with curl. Everything that came from the client, including the user's claimed role, must be re-checked on the server.

Check permissions, not role names, in components (can(user, 'users:delete') instead of user.role === 'admin'). Roles change and multiply; a permission list keeps the UI code stable.

Token expiry and refresh

Access tokens are short-lived on purpose (minutes), so a stolen one stops working quickly. When a request fails with 401, a well-behaved client asks for a new token using the refresh token, then retries the original request once. One subtle problem: if five requests fail at the same moment, you must not send five refresh requests. Share a single in-flight refresh promise.

A fetch wrapper that refreshes once

Three requests all hit 401, but refresh calls: 1 shows that only one refresh went out and the other two waited on the same promise. If the refresh itself fails (the refresh token expired too), clear the user and send them to the sign-in page. Libraries such as TanStack Query, Axios interceptors or your auth provider's SDK implement this for you; understanding it helps you debug them.

The OAuth redirect flow ("Sign in with...")

When users choose "Sign in with Google" (or GitHub, Microsoft...), your app never sees their password. The flow, called authorization code flow with PKCE for browser apps, is:

  1. Your app builds an authorization URL (provider address, your client_id, a redirect_uri, requested scope, a random state, and a PKCE code_challenge) and sends the browser there.
  2. The user signs in and consents on the provider's own page.
  3. The provider redirects back to your redirect_uri with ?code=...&state=....
  4. Your app checks that state matches what you sent (this defeats forged callbacks), then exchanges the code (plus the PKCE code_verifier) for tokens, ideally through your own backend.

The URL handling is plain JavaScript, so we can run it. The values here are fixed for a stable output; real apps generate state and the PKCE verifier from crypto.getRandomValues.

Build the authorize URL and check the callback

In production, do not write this yourself. Use your provider's SDK or a library (Auth.js, Clerk, Auth0, Supabase, Firebase) and a backend or framework that keeps the client secret and tokens away from the browser. Know the steps so you can debug "redirect URI mismatch" errors, which are the most common OAuth problem and usually mean the redirect_uri you send differs from the one registered at the provider.

Security reminders for the React side

  • XSS is the biggest threat to tokens. React escapes text by default; avoid dangerouslySetInnerHTML with untrusted data (see JSX in Depth) and audit third-party scripts.
  • Do not store tokens in localStorage if you can use HttpOnly cookies. If you must, keep lifetimes short.
  • Never put secrets in the bundle. API keys with real privileges stay on the server.
  • Clear client state on sign-out: user data in context, caches (queryClient.clear()), and anything in memory. A shared computer should not show the previous user's data after "back".
  • Sign out on the server too (invalidate the session or revoke the refresh token), not only in React state.
  • Do not decode a JWT and trust it for security decisions. Reading its claims for display is fine; the server verifies the signature.
  • Rate-limit and add multi-factor authentication on the server; the client cannot do either.

Frameworks change the picture a little. With Server Components the session can be checked on the server before any HTML is sent, which removes the flash of a login page and keeps private data out of the browser entirely.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server answers 403 Forbidden. What does it mean?

    401 means not authenticated (who are you?). 403 means authenticated but not authorized (you may not do this).
  2. 2. Why should the auth context have a loading status in addition to signedIn and signedOut?

    Checking an existing session is asynchronous. Until it finishes, a guard should show a loading state instead of redirecting.
  3. 3. You hide the 'Delete user' button from non-admins. Is the app now secure against deleting users?

    Anything in the browser can be changed or bypassed. Hiding controls is a usability feature; enforcement happens on the server.
  4. 4. Why validate the return parameter after login (for example, only allow paths starting with a single slash)?

    The value comes from the URL, which an attacker can craft. Accepting only local paths stops phishing links from bouncing users to other sites.
  5. 5. Five requests fail with 401 at the same time. What is the best behavior for token refresh?

    Sharing one in-flight refresh promise avoids a burst of refresh calls, and avoids invalidating a token that another request just obtained.

Summary

  • Authentication proves who you are (401 when missing); authorization decides what you may do (403 when refused). The server enforces both.
  • Sessions use an HttpOnly cookie the browser sends automatically; tokens are sent in a header and must be stored carefully, ideally in memory with a refresh token in an HttpOnly cookie.
  • Share the user through an auth context with a three-way status (loading, signedIn, signedOut), and make the hook throw when used outside the provider.
  • Protect routes with a guard that redirects to sign-in, remembers the destination, and validates the return path to avoid open redirects.
  • Use permission checks in the UI for good user experience, never as security.
  • Refresh tokens with one shared in-flight request and a single retry.
  • OAuth redirect flows exchange a code (with state and PKCE) for tokens; use a library and keep secrets on a server.
  • Escape output, avoid risky storage, and clear client state on sign-out.

Next: Server Components, Server Functions and Frameworks