Blog | G5 Cyber Security

Single Sign-On (SSO) Guide

TL;DR

This guide shows you how to let users log in once and access multiple parts of your web application without re-entering their details. We’ll cover using cookies and sessions for a secure Single Sign-On (SSO) experience.

1. Understanding the Problem

Without SSO, each section of your web app might ask users to log in separately. This is frustrating and less secure. SSO solves this by verifying the user once and then trusting that verification for other parts of the application.

2. Core Concepts: Cookies & Sessions

3. Implementing SSO – Step by Step

  1. Step 1: Central Authentication Service

    Choose one section of your application to be the central login point. This is where users will enter their username and password.

  2. Step 2: User Login & Session Creation

    When a user successfully logs in, create a session on the server. Store essential user data within this session (e.g., user ID, role).

    // Example using PHP
    session_start();
    $_SESSION['user_id'] = $user_id;
    $_SESSION['role'] = $user_role;
    
  3. Step 3: Setting the Authentication Cookie

    After creating the session, set a cookie on the user’s browser. This cookie will contain a unique identifier (e.g., the session ID). Make sure to set appropriate security flags:

    • HttpOnly: Prevents JavaScript from accessing the cookie, reducing XSS risks.
    • Secure: Only sends the cookie over HTTPS connections.
    • SameSite: Helps prevent CSRF attacks (set to Strict or Lax).
    // Example using PHP
    setcookie('auth_token', session_id(), ['httponly' => true, 'secure' => true, 'samesite' => 'Strict']);
    
  4. Step 4: Protecting Other Application Sections

    In each section of your application that needs authentication, check for the presence and validity of the authentication cookie.

    • Check Cookie Existence: Verify if the ‘auth_token’ cookie exists.
    • Validate Session: If the cookie exists, retrieve the session ID from it and use it to access the user’s session data on the server. If the session is invalid or doesn’t exist, redirect the user to the central login page.
    // Example using PHP
    session_start();
    if (isset($_COOKIE['auth_token'])) {
    session_id($_COOKIE['auth_token']);
      if (!empty($_SESSION['user_id'])) {
        // User is authenticated...
      } else {
        // Session invalid, redirect to login page.
      }
    } else {
      // No cookie found, redirect to login page.
    }
    
  5. Step 5: Logging Out

    When a user logs out, destroy the session on the server and delete the authentication cookie from the browser.

    // Example using PHP
    session_destroy();
    unset($_COOKIE['auth_token']);
    setcookie('auth_token', '', time() - 3600, '/'); // Expire the cookie
    header('Location: /login');
    

4. Security Considerations

5. Advanced Options

Exit mobile version