CyberAbhay
CyberAbhay

Reputation: 534

How to logout user on browser is closed. ie clear JWT token stored in localStorage (not on page refresh)

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

Upvotes: 2

Views: 3562

Answers (1)

hallz
hallz

Reputation: 266

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.

Upvotes: 1

Related Questions