Understanding Single Sign-On (SSO) Mechanism and Java Implementation

This article explains the fundamentals of HTTP session management, the limitations of cookie-based single-system login, and introduces Single Sign-On (SSO) concepts, including global and local sessions, token-based authentication, and provides step-by-step Java code examples for implementing SSO client and server components.

Architect
Architect
Architect
Understanding Single Sign-On (SSO) Mechanism and Java Implementation

1. Single-System Login Mechanism

HTTP is a stateless protocol; each browser request is processed independently by the server. To maintain user state, a session mechanism is introduced where the server creates a session ID and sends it to the browser, which stores it (usually in a cookie) and includes it in subsequent requests.

The server stores the session object in memory, while the browser can transmit the session ID either as a request parameter or via cookies. Cookies store key/value pairs and are automatically sent with each HTTP request, making them the preferred method.

Tomcat implements this with a cookie named JSESSIONID. The login status is stored as an attribute in the session object:

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

Subsequent requests can retrieve the login flag:

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

Only sessions with isLogin=true are allowed to access protected resources.

2. Complexity of Multi-System Environments

Modern web applications consist of multiple subsystems. Requiring users to log in to each subsystem separately is impractical. Ideally, a user logs in once and gains access to the entire application suite.

Cookie-based single-system login cannot be directly applied because cookies are scoped to a domain. Sharing cookies across different domains or heterogeneous platforms (Java, PHP, .NET) is not feasible, and cookies have security drawbacks.

Therefore, a new approach—Single Sign-On (SSO)—is required.

3. Single Sign-On (SSO)

SSO allows a user to authenticate once with a dedicated authentication center and obtain authorization for all subsystems without re‑entering credentials.

Login Process

User accesses a protected resource in System 1; System 1 redirects to the SSO authentication center.

SSO center presents the login page.

User submits credentials; SSO validates them and creates a global session plus an authorization token.

SSO redirects back to System 1 with the token.

System 1 validates the token with the SSO center and creates a local session.

The same flow repeats for System 2, which receives the token and creates its own local session without prompting the user again.

Global and local sessions obey the following rules:

When a local session exists, a global session must exist.

A global session may exist without any local sessions.

Destroying a global session forces destruction of all associated local sessions.

Logout Process

When the user logs out from any subsystem, the subsystem notifies the SSO center, which then invalidates the global session and instructs all registered subsystems to terminate their local sessions.

4. Deployment Diagram

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

5. Implementation (Java)

SSO Client – Login Filter

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 – 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 (e.g., UUID) and storage (e.g., Redis) are used to create and validate authorization tokens. String token = UUID.randomUUID().toString(); Client validates the token with the server:

// Token received as request parameter
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);
}

Upon successful verification, the client creates a local session:

if (verifyResult) {
    session.setAttribute("isLogin", true);
}

Logout handling on the client side:

String logout = req.getParameter("logout");
if (logout != null) {
    this.ssoServer.logout(token);
}

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 to destroy their local sessions:

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

These steps illustrate a complete Java‑based SSO solution, covering session creation, token issuance, validation, and coordinated logout across multiple web applications.

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.

JavaWeb SecuritySession ManagementSSO
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

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.