Course contentsShow
← Node.js
Lesson 1017 of 1,9809. Authentication and Identity ManagementFree lesson

Handling Single Sign-On across Subdomains

Configure authentication to persist seamlessly between multiple related application domains.

In this lesson, you will learn how to configure authentication cookies to allow a user to remain logged in seamlessly as they navigate between different subdomains of your application.

The Challenge of Domain Isolation

By default, browsers follow the "Same-Origin Policy." If a user logs into app.example.com, the browser sets a session cookie specifically for that domain. If the user then navigates to api.example.com or dashboard.example.com, the browser will not automatically send the original cookie, forcing the user to log in again. To solve this for related subdomains, we use Domain Scoping.

Implementing Domain Scoping

To share authentication state across example.com and all its sub-subdomains, you must set your session or JWT-based authentication cookie to be scoped at the parent domain level rather than the specific host level.

When configuring your session middleware (like express-session), you explicitly define the domain property in the cookie configuration using a leading dot:

app.use(session({
  secret: 'your-super-secret-key',
  cookie: {
    domain: '.example.com', // The leading dot includes all subdomains
    httpOnly: true,
    secure: true,
    sameSite: 'lax'
  }
}));

Why the Leading Dot?

Setting the domain to .example.com instructs the browser to treat this cookie as valid for any host ending in .example.com.

Security Considerations

While this makes SSO convenient, it increases the "blast radius" of a potential cookie compromise. Because the cookie is now sent to every subdomain, if any single subdomain (like a less-secure legacy service) is vulnerable to a Cross-Site Scripting (XSS) attack, the attacker could potentially steal the session cookie and gain access to the entire suite of applications.

To mitigate this, ensure that all subdomains participating in your SSO environment enforce the same security standards, such as strict HttpOnly flags and consistent Transport Layer Security (TLS). Always ensure your authentication service is the only one capable of signing and validating the tokens or session identifiers being shared.

Key Takeaway: By setting the domain attribute of your authentication cookie to the parent domain (e.g., .example.com), you enable the browser to persist session identity across all related subdomains seamlessly.