Authentication

Understand how authentication verifies users and authorization controls access in React apps.

Authentication and Authorization in React

Many web applications contain information that should only be accessible to certain users. For example, a customer should be able to view their own orders, while an administrator should have access to manage products and users.

To make this possible, web applications use Authentication and Authorization.

Although these two terms are often used together, they have different meanings:

  • Authentication verifies who you are.
  • Authorization determines what you are allowed to do.

Understanding these concepts is essential for building secure React applications.

What is Authentication?

Authentication is the process of verifying a user's identity.

When a user logs in using an email and password, the application checks whether the provided information is correct.

If the information matches the stored records, the user is successfully authenticated.

Real-World Example

Imagine entering an office building.

A security guard checks your employee ID card.

If the ID is valid, you are allowed to enter the building.

This is authentication: confirming who you are.

What is Authorization?

Authorization happens after authentication.

Once the application knows who you are, it decides which pages or features you can access.

Real-World Example

Inside the office building:

  • Employees can enter their work area.
  • Managers can access meeting rooms.
  • IT administrators can access the server room.

Everyone has different permissions.

This is authorization.

Authentication Flow

A typical login process works like this:

  • The user enters an email and password.
  • React sends the information to the server.
  • The server verifies the credentials.
  • If successful, the server returns a token or session.
  • React stores the login status.
  • The user can access protected pages.

This process keeps unauthorized users out of secure areas.

Simple Login Example

jsx
import { useState } from "react";

function Login() {
  const [loggedIn, setLoggedIn] = useState(false);

  function handleLogin() {
    setLoggedIn(true);
  }

  return (
    <div>
      {loggedIn ? (
        <h2>Welcome!</h2>
      ) : (
        <button onClick={handleLogin}>
          Login
        </button>
      )}
    </div>
  );
}

Explanation

  • loggedIn stores the user's login status.
  • Clicking the button changes the state to true.
  • React displays the welcome message instead of the login button.

In a real application, the login request would be sent to a server for verification.

Protecting Routes

Some pages should only be accessible after a user logs in.

Examples include:

  • Dashboard
  • Profile
  • Orders
  • Checkout
  • Admin Panel

A common approach is to create a Protected Route.

jsx
function ProtectedPage() {
  const loggedIn = true;

  return loggedIn ? (
    <h2>Dashboard</h2>
  ) : (
    <h2>Please Login</h2>
  );
}

If the user is not authenticated, access to the page is denied.

User Roles

Authorization often depends on roles.

Common roles include:

  • User
  • Admin
  • Manager
  • Editor

Example:

jsx
const role = "Admin";

if (role === "Admin") {
  console.log("Access Granted");
}

A regular user may only view products, while an administrator can also create, update, or delete them.

Tokens

After successful authentication, many applications receive a token from the server.

A token is a unique piece of information that proves the user has already logged in.

Instead of asking the user to log in on every page, the application sends the token with future requests.

This provides a smoother user experience while maintaining security.

Where Should Login Information Be Stored?

Applications often store login information using:

  • React Context API
  • Redux Toolkit
  • Browser storage, such as Local Storage or Session Storage
  • Cookies, commonly used with secure server-side authentication

The choice depends on the application's security requirements and architecture.

Real-World Example

Imagine you are building an online shopping website.

Customer

  • Login
  • View products
  • Add items to the cart
  • Place orders

Administrator

  • Login
  • Add products
  • Update prices
  • Manage users
  • View reports

Both users authenticate by logging in, but authorization determines which features each one can access.

Best Practices

When implementing authentication and authorization:

  • Always validate user credentials on the server.
  • Protect sensitive pages from unauthorized access.
  • Hide buttons or menus users should not see.
  • Store authentication data securely.
  • Log users out when their session ends.
  • Never rely only on frontend checks to protect important data.

Remember that frontend checks improve the user experience, but the backend must always enforce security.

Summary

Authentication and authorization are fundamental concepts in web application security. Authentication verifies a user's identity, while authorization controls what that user is allowed to access. In React applications, these concepts are commonly used with login forms, protected routes, user roles, and shared state management. By implementing both correctly and combining them with secure backend validation, you can build applications that are both user-friendly and secure.

Key Takeaways

  • Authentication verifies a user's identity.
  • Authorization determines what a user is allowed to access.
  • Authentication happens before authorization.
  • React commonly uses state and protected routes to manage login status.
  • User roles help control access to different features.
  • Servers often return tokens after successful login.
  • Frontend checks improve the user experience, but backend validation is essential for security.
  • Understanding authentication and authorization is important for building secure React applications.
Let's learn with DevBrainBox AI