Java: ensure web application open only in one browser tab
java, servlet-filters, servlets, session
Solution
I assume your current use case is this:
- The user opens a browser tab, loads your application page and logs in.
The user then opens a second browser tab, loads your application page and is already logged in (because the browser has the same session cookies for all tabs or windows).
And you want to restrict the user so that if when they load the second tab, the instead see a warning message saying: You have already logged into this site elsewhere, please use that window, or if you no longer have that window open, click here to logout and log back in again.
Most solutions will involve keeping a one time token for the instance of the application along with the session. If your application loads up in a single page and presents the user with a login box then when the user logs in you could send the one time token, store it in a javascript variable and send it with all server requests. If the user then loads up the application in a new tab, they request their initial data and the server can generate a response saying that the token is not present and they need to logout, close the window or switch to the already logged in window.
So the answer is baically that you want to store a random string in your session on the server, serve it to the user on login and check that every request has it otherwise bounce them to a logout page. And in the javascript of the web client, store that token and send it with every request to the server.
Problem
What is the best approach to ensure that a specific page (assume a single-page Web application) is open only in one browser tab? Assume the Java Web app has authentication, i.e. user has to sign in (so we can identify which page is being viewed by which user via Java Session API). The intention is that if another tab is opened for the same URL, the user will be redirected to a static page that tells him he has the application open somewhere else (another tab). My current approach fails to work for tabs in the same browser, since `JSESSIONID` is stored in cookies, that are available for all browser's tabs.