Last active
July 31, 2023 06:29
-
-
Save mainul35/b54ba69052fcfcad76989c75961a0086 to your computer and use it in GitHub Desktop.
Invalidate token on closing all browser tabs in a JavaScript application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function manageLoginSession() { | |
let totalTabs: number; | |
window.onload = function(e) { | |
let accessToken = sessionStorage.getItem("accessToken"); | |
let refreshToken = sessionStorage.getItem("refreshToken"); | |
let expiresAt = sessionStorage.getItem("expiresAt"); | |
if (accessToken !== null && refreshToken !== null && expiresAt !== null) { | |
localStorage.setItem("accessToken", accessToken); | |
localStorage.setItem("refreshToken", refreshToken); | |
localStorage.setItem("expiresAt", expiresAt); | |
sessionStorage.removeItem("accessToken"); | |
sessionStorage.removeItem("refreshToken"); | |
sessionStorage.removeItem("expiresAt"); | |
} | |
if (localStorage.getItem("count") === null) { | |
totalTabs = 0; | |
} else { | |
totalTabs = parseInt(localStorage.getItem("count")); | |
} | |
totalTabs++; | |
localStorage.setItem("count", "" + totalTabs); | |
} | |
window.onbeforeunload = function(e){ | |
if (localStorage.getItem("count") === null) { | |
totalTabs = 1; | |
} else { | |
totalTabs = parseInt(localStorage.getItem("count")); | |
} | |
totalTabs--; | |
localStorage.setItem("count", "" + totalTabs); | |
if (totalTabs < 1) { | |
let accessToken = localStorage.getItem("accessToken"); | |
let refreshToken = localStorage.getItem("refreshToken"); | |
let expiresAt = localStorage.getItem("expiresAt"); | |
if (accessToken !== null && refreshToken !== null && expiresAt !== null) { | |
sessionStorage.setItem("accessToken", accessToken); | |
sessionStorage.setItem("refreshToken", refreshToken); | |
sessionStorage.setItem("expiresAt", expiresAt); | |
} | |
localStorage.removeItem("accessToken"); | |
localStorage.removeItem("refreshToken"); | |
localStorage.removeItem("expiresAt"); | |
} | |
} | |
} |
Actually, from the client side, token invalidation is not possible. Only authorization server can invalidate it. I am not sure, which authorization provider you are using, but perhaps you can call the invalidate / logout endpoint along with clearing the token information if the authorization provider has any.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's not invalidating token. It simply removes the token from browser memory without invalidating it. :(