DEV Community

Gideon Iyinoluwa Owolabi
Gideon Iyinoluwa Owolabi

Posted on

How to Implement a single sign-on feature(SSO) across sub-domains on the web using Javascript cookies

Implementing a single sign-on (SSO) feature across sub-domains on the web can help streamline the user authentication process and provide a seamless user experience. In this article, I will discuss how to implement a simple SSO feature using JavaScript cookies.

JavaScript cookies are small text files that are stored on the user's computer by the web browser. They can be used to store small amounts of data,such as user preferences or login information.

In this tutorial implementation, we are using cookies to store the user's login token, which is generated by the server after the user's credentials have been verified. This token can then be sent back to the server on subsequent requests to verify that the user is still logged in.

The "domain" parameter in the document.cookie string is responsible for allowing the cookie to be shared across multiple sub-domains. By setting the domain to .example.com, the cookie will be accessible from any sub-domain of example.com, such as www.example.com or api.example.com. This is what makes the single sign-on feature possible, as the user only needs to log in once and their login status will be maintained across all of the sub-domains.

In this way, cookies provide a simple and convenient way to store and share data between different pages and sub-domains on a website. However, it's important to be aware of the security implications of storing sensitive information in cookies, as they can be easily accessed by malicious actors. To mitigate these risks, it's recommended to use secure cookies and to encrypt any sensitive information stored in them.

To implement SSO using cookies, follow these steps:

1. Create a login page: Create a login page on the primary domain or any other domain (e.g. example.com, auth.example.com) that users can access to log in. This page should have a form that accepts the user's credentials and sends a request to the server to verify the information.

2. Verify user credentials: On the server, verify the user's credentials by comparing them to the values stored in a database. If the credentials are valid, generate a unique token for the user and store it in the database.

3. Set a cookie: If the user's credentials are valid, set a cookie on their device with the token as its value. The cookie should be set to the root domain (e.g. .example.com) so that it can be accessed from all sub-domains.

4. Verify the cookie on each sub-domain: On each sub-domain, check for the presence of the cookie. If the cookie exists and its value is valid, the user is considered to be logged in.

5. Log out the user: To log out the user, simply delete the cookie from their device.

Here is an example of how to implement the above steps in javascript with each step broken down into its own code section:

// Step 1: Create a login page

// Submit the login form
function submitLoginForm() {
  // Get the user's credentials from the form
  const username = document.getElementById("username").value;
  const password = document.getElementById("password").value;

  // Send a request to the server to verify the credentials
  fetch("/verify-credentials", {
    method: "POST",
    body: JSON.stringify({ username, password }),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(response => response.json())
    .then(data => {
      // Step 2: Verify the user's credentials
      if (data.token) {
        // Step 3: Set the cookie
        setCookie("token", data.token);

        // Redirect the user to the home page
        window.location.href = "/home";
      } else {
        // Show an error message if the credentials are invalid
        document.getElementById("error").innerHTML = "Invalid username or password";
      }
    });
}

// Step 3: Set the cookie
function setCookie(name, value) {
  document.cookie = `${name}=${value}; domain=.example.com; path=/;`;
}

// Step 4: Verify the cookie on each sub-domain
function checkCookie() {
  const token = getCookie("token");
  if (token) {
    // The user is logged in
  } else {
    // The user is not logged in
  }
}

// Get the value of a cookie
function getCookie(name) {
  const cookies = document.cookie.split(";");
  for (let cookie of cookies) {
    const [cookieName, cookieValue] = cookie.split("=");
    if (cookieName.trim() === name) {
      return cookieValue;
    }
  }
  return null;
}

// Step 5: Log out the user
function logout() {
  document.cookie = "token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.example.com";
}
Enter fullscreen mode Exit fullscreen mode

Please like and leave a comment if you find this useful. Thank you😊

Top comments (0)