Preventing browsers from sharing sessions across tabs: Tips and tricks

Is there a way to prevent session sharing between multiple browser tabs?

In my JSP/Servlet application using Spring Security, I am interested in achieving the behavior where users are prompted to log in again whenever they switch browser tabs.

Please note: This question is similar to those asked on Stack Overflow and another website. However, these questions were asked several years ago, so I believe there may be updated methods to achieve this. Can anyone provide insight?

Answer №1

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);

Answer №2

Insert the code snippet below on the initial page after logging in

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

Verify the following on all subsequent pages:

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

If a user attempts to open a new tab, the script will redirect them to the login page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking for different elements between two arrays in AngularJS can be achieved by iterating through

I am working with two arrays: $scope.blinkingBoxes=[1,3,2] In addition, I have another array named $scope.clickedBoxes where I push several values. Currently, I use the following code to determine if the arrays are identical: if(angular.equals($scope.bli ...

Create a search preview in JavaScript that emphasizes key information and provides a condensed overview

I am currently working on incorporating a feature that generates a highlighted and condensed preview of a provided text. Below is the code snippet I have so far: <div> Search: <input value='vestibulum' disabled/> </div> < ...

Can Angular retrieve the inner HTML content of an element?

Check out this demo . In this demonstration, I have created a list of "names" and I'm trying to retrieve the text of the selected element. However, whenever I click on an item from the list, I consistently get the same "innerHTML" for all users. Is ...

Vue3 - Managing the Enabling and Disabling of Text Input and Checkbox Based on Input Number

<div class="container-body" v-for="index in 10" :key="index"> <div class="container-content"></div> <div class="container-content"> <input :id="'Row&apo ...

What is the process for refreshing Textures in ThreeJs?

How can I refresh my skybox textures by selecting thumbnails? You can check out this example for reference: canvas_geometry_panorama.html Each thumbnail title corresponds to a folder that contains the skybox images. By using a simple jQuery script, a ...

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

Send the data to the web form along with the JSON information

I find myself in a situation where I am looking for alternative ways to pass data to a redirect page without using querystrings. Here is the current implementation on the Source Page: window.location = "invaliduser.aspx?u=" + encodeURI(username); Consi ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

Tips for concealing navigation buttons during certain stages in react stepzilla

When working with React Stepzilla, I encountered an issue where I have five steps but need to hide the next button on the first step. Following different methods provided online such as: const steps = [ {name: 'Step 1', com ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

Tips for creating a partial matching filter on an array using elements from a separate array

My goal is to filter an array by finding partial matches from another array. To illustrate, consider the following arrays: Array1 = categories: 292300, categories: 300, categories: 292500280 Array2 = 300, 498 After filtering, ...

Three.js - implementing a billboard effect that preserves orientation through camera pans

My situation involves a plane geometry that always faces the camera using the following line of code in the update loop: plane.lookAt(camera.position); While I am utilizing OrbitControls to manipulate the camera, the plane successfully maintains its orie ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

Executing specific rendering procedures based on conditions for mapped data - React

When I map data in the returned render, can I then perform a conditional check on that mapped data? export default function App() { const prod = [ {'name': '1'}, {'name': '2'}, {'name': ' ...

Exporting Blender model to three.js CanvasRenderer results in strange distortion of normals

I'm currently experiencing an issue while trying to export a model using the Three.js import/export tool for Blender. Everything works perfectly fine when I use the WebGLRenderer, but when I switch to CanvasRenderer for cross-browser support, the mode ...

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

JavaScript Class Reference Error

Questioning the mysterious reference error in the JS class from MDN page. The structure of the Bad class's constructor leaves me baffled – is it because the empty constructor calls super() as a default? class Base {} class Good extends Base {} cla ...

Difficulty obtaining elements in Internet Explorer, however works fine in Chrome and Firefox

My <textarea> is set up like this: <textarea class="form-control notetext" id="{{this._id}}-notetext" name="notetext">{{this.text}}</textarea> I am using ajax to send data and load a partial webpage. After loading the content, I attemp ...