Authentication Flow
Authentication Flow covers session lifecycle, login and logout, checking auth state, AuthProvider patterns, and authentication versus authorization.
Course: React — Routing & API Integration Lesson: 12
Learning objectives
Understand a typical SaaS authentication lifecycle, model authentication state, handle login and logout, restore sessions safely, and distinguish authentication from authorization.
Authentication lifecycle
A common flow is:
User opens application|vRestore/check session|+----+----+| |Valid Missing/expired| |App shell Sign-in screen|User signs out / session expires|Clear client session state|Return to public route
The exact flow depends on the backend and identity provider.
Login request
A login form collects credentials and sends them to the approved authentication endpoint over HTTPS. The backend validates the credentials and establishes a session or returns tokens according to the system's design.
Do not invent token storage rules independently of the backend security architecture. HttpOnly, Secure, appropriately scoped cookies can reduce exposure to JavaScript, while token-based designs require careful storage, expiration, refresh, and CSRF/XSS threat analysis.
Model auth state
A useful state model is more expressive than a single boolean:
const initialAuthState = {status: "checking", // checking | authenticated | unauthenticateduser: null};
The checking state prevents the UI from briefly showing the login screen before session restoration has completed.
Auth context and hook
const AuthContext = createContext(null);export function AuthProvider({ children }) {const [auth, setAuth] = useState({status: "checking",user: null});// Restore session using the application's approved session endpoint.// Update auth state after the result is known.const value = {...auth,isAuthenticated: auth.status === "authenticated",setAuthenticatedUser: user =>setAuth({ status: "authenticated", user }),clearSession: () =>setAuth({ status: "unauthenticated", user: null })};return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;}export function useAuth() {const context = useContext(AuthContext);if (!context) throw new Error("useAuth must be used within AuthProvider");return context;}
This illustrates the public API boundary. Production code must connect it to the real session lifecycle and handle failures, expiry, and logout consistently.
Logout and session expiry
Logout should call the backend session-revocation endpoint when required, clear client-side user state, and navigate to an appropriate public page. A 401 response may indicate an expired session; avoid redirect loops by ensuring the login and session endpoints are not themselves handled as protected requests.
Authentication is not authorization
Authentication answers “Who is the user?” Authorization answers “What may this user do?” A signed-in user may still lack access to a billing or administration feature. The backend must enforce both identity and permission checks.
Common mistakes
- Showing protected UI while session status is still being checked.
- Treating any API failure as a logout.
- Storing sensitive credentials in local storage without a threat analysis.
- Forgetting to clear user-specific cached data after logout.
- Assuming a frontend auth context secures backend endpoints.
Best practices
Use HTTPS, follow the identity provider's documented flow, model session restoration explicitly, centralize session expiry behavior, clear user-scoped data on logout, and enforce authorization server-side.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What is the difference between authentication and authorization?
BeginnerModel answer
Authentication establishes who the user is.
Authorization decides what that identity may do.
2What should happen when a session expires?
BeginnerModel answer
Clear client session state, avoid redirect loops, and send the user to an appropriate public route while the backend rejects protected APIs.
Intermediate
3Why is an initial checking auth state useful?
IntermediateModel answer
It prevents flashing the login screen before session restoration finishes, so the UI waits until auth status is known.
4Why must backend endpoints enforce authorization?
IntermediateModel answer
Frontend auth context only shapes UX.
Attackers can call APIs directly, so the server must authorize every sensitive operation.
Advanced
5What are the security tradeoffs of cookie and token approaches?
AdvancedModel answer
HttpOnly Secure cookies reduce JS exposure but need CSRF/session design.
Tokens need careful storage, expiry, refresh, and XSS analysis—follow the backend identity architecture.
Practice
Build a mock login/logout flow with session-checking, authenticated, and unauthenticated states. Add tests for successful login, invalid credentials, session expiry, and logout.