search
HomeWeb Front-endJS TutorialSingle Sign-On (SSO): A Comprehensive Guide with React and ExpressJS

Single Sign-On (SSO) is an authentication mechanism that allows users to log in once and access multiple connected applications or systems without needing to reauthenticate for each one. SSO centralizes user authentication into a single, trusted system (often called an Identity Provider, or IdP), which then manages credentials and issues tokens or session data to verify the user's identity across other services (known as Service Providers, or SPs).

In this guide, we'll explore how SSO works, its benefits and disadvantages, common use cases, and examples of SSO implementation in an API (Node.js with Express), a main application (React), and an external application (React). By understanding the principles and practices of SSO, organizations can enhance user experience, security, and operational efficiency across their applications and systems.

Table of Contents

  • Single Sign-On (SSO)
    • How Does SSO Work?
    • Benefits of SSO
    • Disadvantages of SSO
    • Use Cases for SSO
    • SSO Implementation Examples
    • 1. API (Node.js with Express)
    • 2. Main Application (React)
    • 3. External Application (React)
  • Conclusion

Links

  • GitHub Repository

Demo Video

Single Sign-On (SSO): A Comprehensive Guide with React and ExpressJS

Single Sign-On (SSO)

Single Sign-On (SSO) is an authentication mechanism that allows users to log in once and gain access to multiple connected applications or systems without needing to reauthenticate for each one.

SSO centralizes user authentication into a single, trusted system (often called an Identity Provider, or IdP), which then manages credentials and issues tokens or session data to verify the user's identity across other services (known as Service Providers, or SPs).

How Does SSO Work?

SSO operates through secure token-based mechanisms like OAuth 2.0, OpenID Connect (OIDC), or Security Assertion Markup Language (SAML). Here's a simplified flow:

  • User Login: The user enters their credentials in the Identity Provider (IdP).

  • Token Issuance: The IdP validates the credentials and issues an authentication token (e.g., JWT or SAML assertion).

  • Service Access: The token is passed to the Service Providers, which validate it and grant access without requiring further logins.

Benefits of SSO

  • Enhanced User Experience: Users can access multiple services with a single login, reducing friction and improving usability.

  • Improved Security:

    • Reduces password fatigue, which can lead to unsafe practices like password reuse.
    • Centralized authentication allows for stronger password policies and enforcement of multi-factor authentication (MFA).
  • Simplified User Management:

    • Easier for administrators to manage user access across connected applications.
    • Revoking access to a user from the IdP disables their access to all integrated systems.
  • Time and Cost Efficiency:

    • Saves time for users and support teams by reducing login-related help desk requests.
    • Reduces development time and costs by leveraging existing authentication mechanisms.
  • Compliance and Auditing:

    • Centralized authentication and access control make it easier to enforce security policies and track user activity.

Disadvantages of SSO

  • Single Point of Failure:

    • If the IdP is unavailable or compromised, users cannot access any connected systems.
    • Mitigation: Use redundant IdPs and ensure high availability.
  • Complex Implementation:

    • Integrating SSO requires significant planning and expertise, especially in environments with diverse applications and protocols.
    • Mitigation: Leverage established protocols like OAuth 2.0 or SAML and robust SSO libraries.
  • Security Risks:

    • If an attacker gains access to the user's SSO credentials, they can potentially access all connected systems.
    • Mitigation: Enforce strong MFA and monitor for suspicious login activity.
  • Vendor Lock-In:

    • Organizations may rely heavily on a specific IdP vendor, making migration challenging.
    • Mitigation: Choose open standards and avoid proprietary solutions.
  • Token Management Challenges:

    • Expired or stolen tokens can disrupt access or create security vulnerabilities.
    • Mitigation: Implement token expiration, refresh mechanisms, and secure token storage.

Use Cases for SSO

  • Enterprise Applications:

    • Employees can access various internal tools and services with a single login.
    • Simplifies onboarding and offboarding processes.
  • Cloud Services:

    • Users can seamlessly switch between cloud applications without repeated logins.
    • Enhances productivity and user experience.
  • Customer Portals:

    • Provides a unified login experience for customers across different services.
    • Enables personalization and targeted marketing.
  • Partner Integration:

    • Facilitates secure access to shared resources between partner organizations.
    • Streamlines collaboration and data exchange.

SSO Implementation Examples

1. API (Node.js with Express)

The API acts as the Identity Provider (IdP). It authenticates users and issues JWT tokens for access.

Below is a structured breakdown of the provided code, explaining the purpose of each section for your followers. This serves as a robust example of how to implement SSO functionality in the API layer.

Setup and Dependencies

The following packages are utilized in this setup:

  • express: For handling HTTP requests and routing.
  • jsonwebtoken: For generating and verifying JWTs.
  • cors: For handling cross-origin requests from different client applications.
  • @faker-js/faker: For generating mock user and todo data.
  • cookie-parser: For parsing cookies sent in requests.
  • dotenv: For loading environment variables securely.
Configuration
  • dotenv is used to manage the secret key securely.
  • A fallback secret is provided for development environments.
dotenv.config();
const SECRET_KEY = process.env.SECRET_KEY || "secret";
Middleware
  • CORS ensures that requests from specific front-end origins (main and external-app) are allowed.
  • cookieParser parses cookies sent by clients.
  • express.json allows parsing of JSON request bodies.
app.use(
  cors({
    origin: ["http://localhost:5173", "http://localhost:5174"],
    credentials: true,
  })
);
app.use(express.json());
app.use(cookieParser());

User Authentication and Token Generation

Mock data simulates users and their associated todos.

Users have roles (admin or user) and basic profile information.
Todos are linked to user IDs for personalized access.

  • /login: Authenticates users based on email and password.

Users receive a cookie (sso_token) containing the JWT upon successful login.
This token is secure, HTTP-only, and time-limited to prevent tampering.

app.post("/login", (req, res) => {
  const { email, password } = req.body;
  const user = users.find(
    (user) => user.email === email && user.password === password
  );

  if (user) {
    const token = jwt.sign({ user }, SECRET_KEY, { expiresIn: "1h" });
    res.cookie("sso_token", token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 3600000,
      sameSite: "strict",
    });
    res.json({ message: "Login successful" });
  } else {
    res.status(400).json({ error: "Invalid credentials" });
  }
});
  • /verify: Validates the user’s identity by decoding the token. Invalid tokens result in an unauthorized response.
app.get("/verify", (req, res) => {
  const token = req.cookies.sso_token;

  if (!token) {
    return res.status(401).json({ authenticated: false });
  }

  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    res.json({ authenticated: true, user: decoded });
  } catch {
    res.status(401).json({ authenticated: false, error: "Invalid token" });
  }
});
  • /logout: Clears the cookie containing the JWT token.

Ensures users can log out securely by clearing their token.

dotenv.config();
const SECRET_KEY = process.env.SECRET_KEY || "secret";
  • /todos: Retrieves todos associated with the authenticated user.
app.use(
  cors({
    origin: ["http://localhost:5173", "http://localhost:5174"],
    credentials: true,
  })
);
app.use(express.json());
app.use(cookieParser());
  • /todos: Adds a new todo for the authenticated user.
app.post("/login", (req, res) => {
  const { email, password } = req.body;
  const user = users.find(
    (user) => user.email === email && user.password === password
  );

  if (user) {
    const token = jwt.sign({ user }, SECRET_KEY, { expiresIn: "1h" });
    res.cookie("sso_token", token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 3600000,
      sameSite: "strict",
    });
    res.json({ message: "Login successful" });
  } else {
    res.status(400).json({ error: "Invalid credentials" });
  }
});
  • /todos/:id: Updates a todo based on the provided ID.
app.get("/verify", (req, res) => {
  const token = req.cookies.sso_token;

  if (!token) {
    return res.status(401).json({ authenticated: false });
  }

  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    res.json({ authenticated: true, user: decoded });
  } catch {
    res.status(401).json({ authenticated: false, error: "Invalid token" });
  }
});
  • /todos/:id: Deletes a todo based on the provided ID.
app.post("/logout", (req, res) => {
  res.clearCookie("sso_token");
  res.json({ message: "Logout successful" });
});

2. Main Application (React)

The main application acts as a Service Provider (SP) that consumes the API and manages user interactions.

Below is a structured breakdown of the provided code, explaining the purpose of each section for your followers. This serves as a robust example of how to implement SSO functionality in the main application layer.

  • App Component

The App component manages user authentication and redirects based on login status.

app.get("/todos/:userId", (req, res) => {
  const ssoToken = req.cookies.sso_token;
  const user = getUser(ssoToken);

  if (!user) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  const userTodos = todos.filter((todo) => todo.userId === user.id);
  res.json(userTodos);
});
  • Login Component

The Login component handles user login and redirects to the Todos page upon successful authentication.

app.post("/todos", (req, res) => {
  const ssoToken = req.cookies.sso_token;
  const user = getUser(ssoToken);

  if (!user) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  const { title, description } = req.body;
  const newTodo = {
    id: faker.string.uuid(),
    userId: user.id,
    title,
    description,
  };

  todos.push(newTodo);
  res.status(201).json({ message: "Todo added successfully", data: newTodo });
});
  • Todos Component

The Todos component displays user-specific todos and allows adding and deleting todos.

// Update a todo
app.put("/todos/:id", (req, res) => {
  const ssotoken = req.cookies.sso_token;
  const user = getUser(ssotoken);
  if (!user) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  const { id } = req.params;
  const { title, description } = req.body;
  const index = todos.findIndex((todo) => todo.id === id);

  if (index !== -1) {
    todos[index] = {
      ...todos[index],
      title,
      description,
    };
    res.json({
      message: "Todo updated successfully",
      data: todos[index],
    });
  } else {
    res.status(404).json({ message: "Todo not found" });
  }
});

3. External Application (React)

The external application acts as another Service Provider (SP) that consumes the API and manages user interactions.

Below is a structured breakdown of the provided code, explaining the purpose of each section for your followers. This serves as a robust example of how to implement SSO functionality in the external application layer.

  • App Component

The App component manages user authentication and redirects based on login status.

// Delete a todo
app.delete("/todos/:id", (req, res) => {
  const ssoToken = req.cookies.sso_token;
  const user = getUser(ssoToken);
  if (!user) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  const { id } = req.params;
  const index = todos.findIndex((todo) => todo.id === id);

  if (index !== -1) {
    todos = todos.filter((todo) => todo.id !== id);
    res.json({ message: "Todo deleted successfully" });
  } else {
    res.status(404).json({ message: "Todo not found" });
  }
});
  • Todos Component

The Todos component displays user-specific todos.

import { useState, useEffect } from "react";
import {
  Navigate,
  Route,
  Routes,
  useNavigate,
  useSearchParams,
} from "react-router-dom";
import Todos from "./components/Todos";
import Login from "./components/Login";
import { toast } from "react-toastify";
import api from "./api";

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  useEffect(() => {
    const verifyLogin = async () => {
      const returnUrl = searchParams.get("returnUrl");
      try {
        const response = await api.get("/verify", {
          withCredentials: true,
        });
        if (response.data.authenticated) {
          setIsLoggedIn(true);
          toast.success("You are logged in.");
          navigate("/todos");
        } else {
          setIsLoggedIn(false);
          if (!returnUrl) {
            toast.error("You are not logged in.");
          }
        }
      } catch (error) {
        setIsLoggedIn(false);
        console.error("Verification failed:", error);
      }
    };

    verifyLogin();

    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        verifyLogin();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [navigate, searchParams]);

  return (
    <div classname="container p-4 mx-auto">
      <routes>
        <route path="/" element="{<Login"></route>} />
        <route path="/todos" element="{isLoggedIn"></route> : <navigate to='{"/"}'></navigate>}
        />
      </routes>
    </div>
  );
}

export default App;

Conclusion

Single Sign-On (SSO) simplifies user authentication and access management across multiple applications, enhancing user experience, security, and operational efficiency. By centralizing authentication and leveraging secure token-based mechanisms, organizations can streamline user access, reduce password-related risks, and improve compliance and auditing capabilities.

While SSO offers numerous benefits, it also presents challenges such as single points of failure, complex implementation requirements, security risks, and potential vendor lock-in. Organizations must carefully plan and implement SSO solutions to mitigate these risks and maximize the benefits of centralized authentication.

By following best practices, leveraging established protocols, and choosing open standards, organizations can successfully implement SSO to enhance user experience, security, and operational efficiency across their applications and systems.

The above is the detailed content of Single Sign-On (SSO): A Comprehensive Guide with React and ExpressJS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor