Mastering Single Sign-On: From Session Basics to Java Implementation

This article explains the stateless nature of HTTP, introduces session and cookie mechanisms for single‑system login, discusses the challenges of multi‑system applications, and provides a step‑by‑step guide with Java code to implement Single Sign‑On (SSO) including login, token verification, global and local sessions, and coordinated logout.

IT Architects Alliance
IT Architects Alliance
IT Architects Alliance
Mastering Single Sign-On: From Session Basics to Java Implementation

HTTP Statelessness and Session Basics

HTTP is a stateless protocol, meaning each request is processed independently without any built‑in link to previous or subsequent requests. To protect server resources, a session mechanism is introduced so that the server and browser jointly maintain state.

Single‑System Login Mechanism

When a browser first accesses a server, the server creates a session and returns a session ID (e.g., JSESSIONID) via a cookie. Subsequent requests include this cookie, allowing the server to recognize the same user.

Example code for setting a login flag in a Tomcat session:

HttpSession session = request.getSession();
session.setAttribute("isLogin", true);

Checking the flag on later requests:

HttpSession session = request.getSession();
session.getAttribute("isLogin");

Complexity of Multi‑System Applications

Modern web applications consist of many subsystems. Requiring users to log in to each subsystem is impractical. Cookies are scoped to a domain, so sharing a session across different domains (or different technology stacks) is limited.

Single Sign‑On (SSO) Overview

SSO (Single Sign‑On) allows a user to authenticate once with a central SSO server and then access all registered subsystems without additional logins. It introduces two kinds of sessions:

Global session : Managed by the SSO server.

Local session : Managed by each subsystem after receiving a valid token.

The flow involves the user being redirected to the SSO server, authenticating, receiving an authorization token, and the token being used by subsystems to create local sessions.

SSO Login Process (Step‑by‑Step)

User accesses a protected resource in Subsystem 1; the subsystem redirects to the SSO server with its URL as a parameter.

SSO server detects the user is not logged in and redirects to the login page.

User submits credentials; the SSO server validates them and creates a global session.

SSO server generates a random token (e.g., UUID.randomUUID().toString()) and stores it (commonly in Redis).

SSO server redirects back to Subsystem 1, appending the token.

Subsystem 1 receives the token, calls the SSO server to verify it, and upon success creates a local session.

The same token can be used by Subsystem 2, which follows the same verification and local‑session creation steps.

SSO Logout Process (Step‑by‑Step)

User initiates logout in Subsystem 1 (e.g., by sending a request with a logout parameter).

Subsystem 1 forwards the logout request to the SSO server.

SSO server invalidates the global session and retrieves the list of registered subsystems (stored alongside the token).

SSO server notifies each registered subsystem to invalidate its local session.

Each subsystem destroys its local session and optionally redirects the user to a post‑logout page.

Implementation Details (Java)

SSO Client (Filter) – intercepts requests, checks the isLogin attribute, and redirects unauthenticated users to the SSO server.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession();
    if (session.getAttribute("isLogin")) {
        chain.doFilter(request, response);
        return;
    }
    // redirect to SSO server with original URL
    res.sendRedirect("sso-server-url-with-system-url");
}

When a token is present in the request, the filter verifies it via the SSO server:

String token = req.getParameter("token");
if (token != null) {
    boolean verifyResult = this.verify("sso-server-verify-url", token);
    if (!verifyResult) {
        res.sendRedirect("sso-server-url");
        return;
    }
    chain.doFilter(request, response);
}

SSO Server – Login Endpoint

@RequestMapping("/login")
public String login(String username, String password, HttpServletRequest req) {
    this.checkLoginInfo(username, password);
    req.getSession().setAttribute("isLogin", true);
    return "success";
}

Token generation: String token = UUID.randomUUID().toString(); Token verification typically looks up the token in Redis (which also stores the list of subsystem URLs that have registered the token). Redis provides fast in‑memory access and TTL support for token expiration.

SSO Server – Logout Endpoint

@RequestMapping("/logout")
public String logout(HttpServletRequest req) {
    HttpSession session = req.getSession();
    if (session != null) {
        session.invalidate(); // triggers LogoutListener
    }
    return "redirect:/";
}

LogoutListener notifies all registered subsystems (using an HTTP client) to destroy their local sessions.

public class LogoutListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {}
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        // send logout request to each registered subsystem via HttpClient
    }
}

The overall architecture consists of an SSO server (authentication center) and multiple SSO clients (subsystems). Communication can be implemented with HTTP client libraries, RESTful APIs, RPC, or web services.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentTokenSession ManagementSSOWeb Authentication
IT Architects Alliance
Written by

IT Architects Alliance

Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.