1

I am using JWT token with msal for user authentication. Once user is logged in then we store the JWT token in the localStorage and on logout we clear the localStorage along with msal loguut.

But i wanted to force logout the user on the browser is closed.So for this i have to clear the localStorage once the browser is closed.

I tried to use onbeforeunload & onunload method for this but this methods get called on page refresh also. - tried to use sessionStorage but this cause user to login on each tabs cos of its tab specific scope.

I tried following code

componentDidMount() {
   window.addEventListener("beforeunload",this.forceLogout,false)
}

componentWillUnmount() {
    window.removeEventListener("beforeunload",this.forceLogout,false)
}

forceLogout(){
  localStorage.clear();
}

Note: after msal login redirect back to application we refresh the page because of using HashRouter

31piy
  • 23,323
  • 6
  • 47
  • 67
CyberAbhay
  • 494
  • 6
  • 17

1 Answers1

1

If you use the session cache storage option in MSAL.js then the tokens will be cleared by the browser when it is closed.

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/383c2e3089f139daaaaf7b81a80bc8c47b6c1273/lib/msal-core/README.md#cache-storage

However take care if you have multiple windows/tabs open of your app as the browser probably clear until all instances are closed.

hallz
  • 236
  • 4
  • 6
  • No, i am using localStorage and it does not get cleared on browser/tab closed.. – CyberAbhay Feb 04 '20 at 04:53
  • @CyberAbhay Yes, sorry my answer was suggesting that you change to use session storage option (this is same as browser local storage but only persisted for browser session) as it should behave how you want on browser close. – hallz Feb 05 '20 at 05:22
  • Yes i got what you suggested. But using sessionStorage user login is limited the single tab only and login status is not shared across the tabs. So i cant use session storage. – CyberAbhay Feb 05 '20 at 06:45