Authentication

A Secure SSO System with Cross-Domain Token Authentication

AminAmin
June 2, 2025
Featured
A Secure SSO System with Cross-Domain Token Authentication

Problem

Users hate logging in multiple times. You have cpanel.unifyed.tech, dash.unifyed.tech and few more apps - but each asking for separate login? That's bad UX.

Solution Architecture

One auth domain (auth.unifyed.tech) issues JWT tokens. All subdomains trust this token via shared cookies.

The Flow

  1. User hits cpanel.unifyed.tech/dashboard
  2. App checks for authToken cookie
  3. No cookie? Redirect to auth.unifyed.tech/login?redirect=cpanel.unifyed.tech/dashboard
  4. User logs in → server sets cookie on Domain=.unifyed.tech
  5. Redirect back to original app → now user is authenticated everywhere
const token = getCookie("authToken");
if (!token) {
  window.location.href = `https://auth.unifyed.tech/login?redirect=${encodeURIComponent(
    currentURL
  )}`;
}

This is the core trick - we set JWT in a cookie with these flags

document.cookie = `authToken=${token}; Domain=.unifyed.tech; Path=/; Secure; HttpOnly; SameSite=None`;

Security Stuff

Always validate redirect URLs against whitelist

const allowedDomains = /^https?:\/\/[^\/]+\.unifyed\.tech/;
if (!allowedDomains.test(redirectUrl)) {
  throw new Error("Invalid redirect");
}

Each app validates JWT server-side on every request

app.get("/api/validate-token", (req, res) => {
  const token = req.cookies.authToken;
  const user = jwt.verify(token, SECRET_KEY);
  res.json({ user });
});

Logout Everywhere

When user logs out from any app we need to clear session from all tabs:

document.cookie = "authToken=; Domain=.unifyed.tech; Path=/; Max-Age=0";

const bc = new BroadcastChannel("auth");
bc.postMessage({ cmd: "logout" });

bc.onmessage = (event) => {
  if (event.data?.cmd === "logout") {
    handleLogout();
  }
};

Final Thoughts

This SSO implementation gives you enterprise-level user experience without the enterprise complexity. Users login once and access everything - exactly what SSO should do.

The beauty is in simplicity. One auth domain, shared cookies and proper validation. That's it.

Perfect for mid-size applications who want proper SSO without dealing with Okta pricing or SAML complexity.

TagsSSOJWTOAuth2React

References