How to NOT share session between multiple browser tabs ?
I am using Spring Security in JSP/Servlet application and I want to know "How can we achieve the behavior with Spring Security where user is forced to login again whenever he changes the browser tab ?".
Disclaimer
Question is similar to this Question and this question, but since both the questions are too old (i.e. 4,7 years old) I am sure there must be some way to achieve that today, isn't it ?
On successful login put some value in sessionStorage.setItem('userId',userId) and when ever user open new tab and tries to login check if sessionStorage.getItem('userId') is available if null it means it is a new tab / redirect to login page.
Session storage is tab specific and data are not shared between different tabs. Session storage runs in modern browser.
check this link for details
Try below code
On successful login add this below code
<script>
if(typeof(Storage) !== "undefined") {
sessionStorage.setItem("uniqueIdSessionStorage", "xyz");
}
</script>
sessionStorage.getItem('uniqueIdSessionStorage') // this will be a tab specific you will not get xyz for other tabs.
1) Check if sessionStorage.getItem('uniqueIdSessionStorage') is not null, if null means new tab and new user.
2) On server side always store session attributes like below code
session.setAttribute("userId"+UniqueValuePerUser,userId);
3) This way you can have multiple login with single session object for every user key will be unique.
4) Pass sessionStorage value server side somehow in request Parameter. One way is to send in url or somewhere hidden in input.
5) Now if you get 12345 value from tab. Then get details from session using below code
String uniqueId= request.getParameter("uniqueId"); // value will be 12345
session.getAttribute("userId"+uniqueId);
and if you get 45678 value from tab then
String uniqueId= request.getParameter("uniqueId"); // value will be 45678
session.getAttribute("userId"+uniqueId) // and other details from session using unique id;
6) This way with unique key in single session you can achieve multiple login but if one logout and you invalidate session other user will also get logged out because session object is one with unique key.
7) Instead of invalidate session remove that particular key from session.
session.removeAttribute("userId"+uniqueId);
Put below script on first page after login
<script>
window.name = 'appname';
</script>
check following on all the other pages:
if (window.name != 'appname'){
window.location = "/login.jsp";
}
If user will try to open the new tab, script will take user to login page.