When a user successfully logs in, store a value using sessionStorage.setItem('userId', userId). If the user opens a new tab and tries to login, check if sessionStorage.getItem('userId') is available. If it is null, redirect them to the login page as it indicates a new tab.
It's important to note that session storage is specific to each tab, and data is not shared between different tabs. Session storage functions in modern browsers.
For more information, you can refer to this link.
Try out the code below:
Include the following code after successful login:
<script>
if(typeof(Storage) !== "undefined") {
sessionStorage.setItem("uniqueIdSessionStorage", "xyz");
}
</script>
sessionStorage.getItem('uniqueIdSessionStorage') // This value will be specific to the tab and won't be accessible in other tabs.
1) Check if sessionStorage.getItem('uniqueIdSessionStorage') is not null. If it is null, it implies a new tab with a new user.
2) Always store session attributes on the server side using code like the one below:
session.setAttribute("userId"+UniqueValuePerUser, userId);
3) Using unique keys for each user, you can have multiple logins with a single session object where every user key is unique.
4) Somehow pass the sessionStorage value to the server side in the request parameter. One option is to send it in the URL or hide it in an input field.
5) If you receive a value of 12345 from a tab, retrieve details from the session using the following code:
String uniqueId= request.getParameter("uniqueId"); // The value will be 12345
session.getAttribute("userId"+uniqueId);
If you receive a value of 45678 from a tab, then use the following code:
String uniqueId= request.getParameter("uniqueId"); // The value will be 45678
session.getAttribute("userId"+uniqueId); // Retrieve other details from the session using the unique id;
6) With a unique key in a single session, you can achieve multiple logins. However, if one user logs out and you invalidate the session, all users sharing that session key will also get logged out.
7) Instead of invalidating the session, remove the specific key from the session.
session.removeAttribute("userId"+uniqueId);