📘 ReactJS

Authentication & Authorization

Authentication identifies a user. Authorization determines what that user is permitted to do. A production React application normally handles authentication state, protected routes, session expiration, permission-based UI, and API authorization while relying on the backend as the security authority.

S

Site Administrator

📅 Sep 28, 2026 🕒 2 min read 👁 30 views
☆ Save 𝕏 in f ✆
Authentication & Authorization

Authentication identifies a user. Authorization determines what that user is permitted to do. A production React application normally handles authentication state, protected routes, session expiration, permission-based UI, and API authorization while relying on the backend as the security authority.

Authentication flow

sequenceDiagram
participant User
participant React
participant Auth
participant API
User->>React: Login credentials
React->>Auth: Authenticate
Auth-->>React: Authenticated session
React->>API: Protected request
API-->>React: Data

Authentication state

const AuthContext = createContext(null);

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  async function loadCurrentUser() {
    const response = await api.get("/me");
    setUser(response.data);
  }

  return (
    <AuthContext.Provider value={{
      user,
      loadCurrentUser
    }}>
      {children}
    </AuthContext.Provider>
  );
}

Authorization with permissions

const permissions = [
  "orders.read",
  "orders.create",
  "reports.read"
];

function Can({ permission, children }) {
  const allowed = permissions.includes(permission);

  return allowed ? children : null;
}

Important security boundary

Hiding an Admin button is not authorization. The backend must reject unauthorized API requests even when a user manually constructs the request.

// Backend must still enforce:
POST /api/admin/users

Authenticated user:
permission = users.manage

Result:
403 Forbidden

Session expiration

When a protected API returns 401, the frontend can clear stale authentication state and redirect the user to login. Avoid infinite redirect loops and coordinate multiple simultaneous 401 responses.

Output

Signed in as Ravi

Dashboard
Orders
Reports
Admin

If Ravi lacks users.manage:

Dashboard
Orders
Reports

Admin screen:
Access denied

Common mistakes

  • Treating frontend visibility as security.
  • Assuming authentication automatically grants permissions.
  • Keeping authorization rules only in the frontend.
  • Not handling session expiration.
  • Logging credentials or tokens.

Interview questions

  • Authentication vs authorization?
  • Where should authorization be enforced?
  • How should React handle a 401?
  • How would you model permissions?

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.

Never miss a new post 📬

Get an email whenever a new article, project, cheatsheet or video drops.

✅

ℹ️