How Single Sign-On (SSO) Works: From Session Basics to Full Implementation

This article explains the stateless nature of HTTP, how session and cookie mechanisms enable login state in a single web system, the challenges of multi‑system environments, and provides a step‑by‑step guide with code examples for building a Java‑based Single Sign‑On solution, including token generation, validation, and logout handling.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
How Single Sign-On (SSO) Works: From Session Basics to Full Implementation

Single System Login Mechanism

HTTP is a stateless protocol, meaning each request is processed independently without any built‑in link to previous or future requests. To protect server resources, browsers must be identified and authorized, which is achieved by maintaining a session state shared between client and server.

The server creates a session on the first request, returns a session ID (e.g., JSESSIONID) to the browser, and the browser includes this ID in subsequent requests via cookies. The server stores the session object in memory, while the browser stores the session ID in a cookie.

HTTP stateless illustration
HTTP stateless illustration

Login status is stored as an attribute in the session object, for example:

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

Subsequent requests check this attribute to determine if the user is authenticated.

Login state flow
Login state flow

Complexity of Multi‑System Environments

Modern web applications consist of multiple subsystems. Requiring users to log in to each subsystem separately is impractical. Cookies, which carry the session ID, are scoped to a domain, so sharing a session across different domains (or technologies) is limited.

Multi‑system login challenge
Multi‑system login challenge

Because cookie domains must match, a unified login solution is needed—this is where Single Sign‑On (SSO) comes in.

Single Sign‑On (SSO)

SSO allows a user to authenticate once with a dedicated authentication center (SSO server) and gain access to all registered subsystems without re‑entering credentials. The process relies on an authorization token passed between the SSO server and each subsystem.

SSO token flow
SSO token flow

Key steps of the SSO login flow:

User accesses a protected resource in Subsystem 1; the subsystem redirects to the SSO server.

SSO server presents the login page.

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

SSO server generates a random token (e.g., UUID.randomUUID().toString()) and redirects back to Subsystem 1 with the token.

Subsystem 1 validates the token with the SSO server, creates a local session, and grants access.

When the user later accesses Subsystem 2, the SSO server recognizes the existing global session and directly issues a token, allowing seamless access.

Global and local sessions have the following relationship:

Local session existence implies global session existence.

A global session may exist without a corresponding local session.

Destroying the global session must also destroy all associated local sessions.

Deployment Diagram

The SSO architecture consists of an SSO server (authentication center) and multiple SSO clients (subsystems). Clients must integrate an SSO client component to handle token exchange, validation, and logout notifications.

SSO deployment diagram
SSO deployment diagram

Implementation Details (Java)

SSO Client responsibilities:

Intercept unauthenticated requests (e.g., via a Filter) and redirect to the SSO server.

Receive and store the token returned by the SSO server.

Validate the token with the SSO server.

Create a local session upon successful validation.

Intercept logout requests and forward them to the SSO server.

Handle logout notifications from the SSO server to destroy the local session.

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
    res.sendRedirect("sso-server-url-with-system-url");
}

SSO Server responsibilities:

Validate user credentials and create a global session.

Generate an authorization token (e.g., String token = UUID.randomUUID().toString();).

Store tokens and associated subsystem URLs in a fast key‑value store such as Redis.

Provide token validation endpoints for clients.

Handle logout requests, invalidate the global session, and notify all registered subsystems.

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

Token validation example using HttpClient:

HttpPost httpPost = new HttpPost("sso-server-verify-url-with-token");
HttpResponse httpResponse = httpClient.execute(httpPost);

Logout flow:

User triggers logout in a subsystem; the subsystem sends a logout request (including the token) to the SSO server.

SSO server invalidates the global session, looks up all registered subsystem URLs, and sends logout notifications to each.

Each subsystem receives the notification and destroys its local session.

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

A listener can broadcast logout requests to all registered subsystems:

public class LogoutListener implements HttpSessionListener {
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        // Use HttpClient to send logout requests to all registered systems
    }
}

By following these steps, developers can implement a functional SSO solution that centralizes authentication, shares login state across multiple applications, and ensures consistent logout behavior.

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.

JavaAuthenticationServletTokenSession ManagementSSO
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

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.