Erase Access Token on closing all tabs of a domain or the browser

Syed Hasan
2 min readFeb 25, 2020

--

Erase token on browser close

Disclaimer: This can be achieved in different ways. I will only demonstrate one way to do this.

Problem Scenario

It is often a usual case that if access token is not invalidated, then it may remain alive in your browser storage (localStorage, cookie etc.) and may be reused if the site in visited next time. What if someone else enters into the same domain and finds your active session? This will be a security vulnerability. To avoid this, a solution can be removing tokens on closing all the tabs or the whole browser.

Well, but there are some common problems!

  • It is not a usual scenario that browser will provide you an API by which your program will know if your current tab is the last tab of a domain.
  • Let’s assume you have managed to know that current tab is the last one, but still if a user reloads this tab, and your browser unloads contents and loads again, there is a chance that you may lose your previous tokens.

The Solution

  • We will use localStorage for sharing same data of a domain among tabs of same browser.
  • We will use sessionStorage for keeping state of the same tab while reloading.
  • We will use onbeforeunload event to perform actions on tab close.
  • We will use onload event to perform actions on loading data of a tab.

Our way-around is, we will count tabs and store the counting in localStorage so that it can be shared among all tabs. We will remove tokens stored in localStorage when page unloads (onbeforeunload) and tab counting goes less than 1. However, during reload, first a page unloads and then loads data again. Hence, we will use SessionStorage to store tokens and validity. Then the same tab loads again (onload), we will read token details from sessionStorage and again store the token details in localStorage.

--

--

Syed Hasan
Syed Hasan

Written by Syed Hasan

Software Engineer | Back-End Developer | Spring Developer | Cloud Enthusiast

No responses yet