Authentication Handling
Definition
The process of verifying user identity (Login), maintaining their session across page reloads (Tokens/Cookies), and protecting certain React routes from unauthorized access.
Explain Like I'm New
Authentication is like getting a wristband at a concert. First, you show your ID at the front door (Login). The bouncer gives you a wristband (Token). Now, whenever you want to enter the VIP area (Protected Route), the security guard just checks if you are wearing the wristband. If not, they kick you back to the front door (Redirect to Login).
Real World Example
A user logs in. The backend returns a JWT (JSON Web Token). The React app stores this token and wraps the `<Dashboard>` component in a `<ProtectedRoute>`. If a guest tries to visit `/dashboard`, the route checks for the token, finds nothing, and redirects to `/login`.
Common Use Cases
- •Protecting Private Routes
- •Displaying different UI for guests vs logged-in users
- •Attaching Bearer tokens to outgoing API requests
Interactive Example
import React, { useState, createContext, useContext } from 'react'; const AuthContext = createContext(); function ProtectedRoute({ children }) { const { user } = useContext(AuthContext); if (!user) { return <div className='text-red-500 font-bold p-4 border'>Access Denied. Please log in!</div>; } return children; } export default function AuthDemo() { const [user, setUser] = useState(null); return ( <AuthContext.Provider value={{ user, setUser }}> <div className='p-4 border'> <header className='flex justify-between mb-4'> <h2>MyApp</h2> {user ? <button onClick={() => setUser(null)}>Logout</button> : <button onClick={() => setUser({ name: 'Alice' })} className='bg-blue-500 text-white px-2 rounded'>Login</button> } </header> <p>Everyone can see the homepage.</p> <div className='mt-4'> <h3>Dashboard:</h3> <ProtectedRoute> <div className='bg-green-100 p-4 rounded'>Welcome to the secret dashboard, {user?.name}!</div> </ProtectedRoute> </div> </div> </AuthContext.Provider> ); }
Interview Questions
basic
- How do you protect a route in React?
- Where should you store the user's authentication state (isLoggedIn)?
intermediate
- What is a Higher Order Component (HOC) and how is it used for Auth?
- How do you persist the user's login after they close the browser?
advanced
- What is the difference between Authentication (401) and Authorization (403)?
- How do you handle silent token refresh in React?