Java: make sure the web application is open in only one browser tab

What is the best approach to ensure that a particular page (assuming a single-page web application) opens in only one browser tab?

Suppose a Java web application has authentication, that is, the user must log in (so that we can determine which page the user is viewing through the Java Session API).

It is assumed that if another tab is opened for the same URL, the user will be redirected to a static page, which says that he has an application open somewhere else (another tab).

My current approach does not work for tabs in the same browser, since JSESSIONID is stored in cookies, which are available for all browser tabs.

+4
source share
2 answers

I assume your current use case is as follows:

  • The user opens a browser tab, loads your application page and logs in.

Then the user opens the second tab of the browser, loads your application page and already logs in (since the browser has the same cookies for all tabs or windows).

And you want to limit the user so that when loading the second tab a warning message appears instead: "You are already logged in to this site elsewhere, use this window or if you no longer have this window open, click here to log out and log in again.

Most solutions will use a one-time token for the application instance along with the session. If your application loads on one page and presents the user with a login window, then when the user logs in, you can send a one-time token, save it in a javascript variable and send it with all server requests. If the user downloads the application to a new tab, they request their initial data, and the server can generate a response saying that there is no token, and he needs to log out, close the window or switch to the already registered window.

Thus, the answer is important that you want to store a random string in your session on the server, submit it to the user when you log in, and check that each request has otherwise bounced them to the exit page. And in javascript of the web client, store this token and send it with each request to the server.

+6
source

You can create an asynchronous backend call (keyword: long polling) and send single bytes through it to keep it alive. While he is alive, the tab is open. If a second call comes in, you can check it out.

0
source

All Articles