I'm using AWS Cognito and aws-amplify to manage user authentication. When I load up my app, I call Auth.currentSession() which seems to always return the user I was logged in as if I do not explicitly log out by calling Auth.signOut().
I'm fine with this should the user choose a "keep user logged in", but if they don't, how would I go about making sure the user gets logged out once they leave the app?
I tried adding an event listener in my login() method but that didn't work i.e. the user was still logged in when I returned to the app:
.
.
.
if (!keepSignedIn) {
window.addEventListener('unload', function(event) {
Auth.signOut();
});
}
I'm pretty sure the logout() method creates a promise - it operates asynchronously. So the page is probably being destroyed before the promise's logout code is executed.
You can confirm this by executing console.log(Auth.signOut());. If it's a promise it'll log Promise { <pending> }
There's no way to halt unloading of the page, as that would be bad if we could.
What you need is a synchronous signout function. Fortunately, you can just clear the browser local storage, which is a synchronous operation. (Local storage is where Amplify stores the auth tokens.)
if (!keepSignedIn) {
window.addEventListener('unload', function(event) {
localStorage.clear();
});
}
Depending on your situation you may need to instead find and remove individual local storage items, instead of clearing them all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With