Reputation: 534
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
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.
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