I am using cookies authentication in my .net core mvc application. One of the requirements I have is to logout user when the browser is closed. I have set sliding expiration to 5 minutes in app. As expected if the user comes back to the website after 5 minutes user is redirected to login page, but if the user comes back inside 5 minutes the user is logged in automatically. Is there a way to logout user if the browser is closed?
1 Answer
There is no direct way of detecting if the browser is closed, however you can certainly check if the tab has been closed. You can use the following ways, in order of sophistication:
Unload Event
Listen for the unload
event on your <body>
tag:
<html>
<body onunload="tellServerBrowserClosed()">
<!--...-->
Caveat: Will fire even when you leave a site over a link (within the same site) or your browsers back button. (not a good solution
)
Ajax Beacon
Simply send Ajax GET
requests against an API from the browser (which should have the user's cookies) at a regular (20-60 second interval). When 2-3 beacon's (API calls) have been missed, clear that user's data.
Caveat: You need to implement a server side cronjob to deal with expired beacons
WebSockets
Use a WebSocket connection (maybe Socket.io). This way as soon as the user closes the tab, the connection closes, and you can use this event to clear their session. (For added accuracy, you may want to keep track of multiple socket connections from the same user, in case they use more than 1 tab)
-
-
-
Yeah, also thought if WebSockets could be used. SignalR is easy to implement in .NET Core. Setup a hub, keep track of the same client connecting, when the count is zero, delete the session from the database (if such exists)– MichaelCommented Apr 11, 2019 at 19:38