如何阻止浏览器在选项卡之间共享会话?

How to STOP browsers from sharing session amongst tabs?

如何在多个浏览器选项卡之间共享会话?

我在 JSP/Servlet 应用程序中使用 Spring 安全性,我想知道 "How can we achieve the behavior with Spring Security where user is forced to login again whenever he changes the browser tab ?".

免责声明 问题类似于 this Question and this question,但由于这两个问题都太老了(即 4.7 岁),我相信今天一定有某种方法可以实现,不是吗?

登录后第一页放下面脚本

<script>
    window.name = 'appname';
</script>

检查所有其他页面上的以下内容:

if (window.name != 'appname'){
    window.location = "/login.jsp";
}

如果用户尝试打开新选项卡,脚本会将用户带到登录页面。

成功登录后,在 sessionStorage.setItem('userId',userId) 中输入一些值,当用户打开新选项卡并尝试登录时,检查是否 sessionStorage.getItem('userId' ) 如果为 null 则可用,这意味着它是一个新选项卡/重定向到登录页面。

会话存储是特定于选项卡的,不同选项卡之间不共享数据。会话存储在现代浏览器中运行。

查看此 link 了解详细信息

试试下面的代码

登录成功后添加下面的代码

<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) 检查sessionStorage.getItem('uniqueIdSessionStorage')是否不为空,如果为空则表示新标签页和新用户。

2) 在服务器端总是像下面的代码一样存储会话属性

 session.setAttribute("userId"+UniqueValuePerUser,userId);

3) 这样您就可以使用单个会话对象进行多次登录,因为每个用户密钥都是唯一的。

4) 在请求参数中以某种方式传递 sessionStorage 值服务器端。一种方法是发送 url 或隐藏在输入中的某个地方。

5) 现在,如果您从选项卡中获得 12345 值。然后使用以下代码从会话中获取详细信息

String uniqueId= request.getParameter("uniqueId"); // value will be 12345
session.getAttribute("userId"+uniqueId);

如果您从选项卡中获得 45678 值,则

String uniqueId= request.getParameter("uniqueId"); // value will be 45678
session.getAttribute("userId"+uniqueId) // and other details from session using unique id;

6) 这种在单个会话中使用唯一密钥的方式可以实现多次登录,但是如果一个注销并且您使会话无效,其他用户也将被注销,因为会话对象是一个具有唯一密钥的对象。

7) 从会话中删除该特定密钥,而不是使会话无效。

session.removeAttribute("userId"+uniqueId);