.net核心cookie身份验证在浏览器上关闭 [英] .net core cookies authentication on browser close

查看:123
本文介绍了.net核心cookie身份验证在浏览器上关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.net核心mvc应用程序中使用cookie身份验证.我的要求之一是在浏览器关闭时注销用户.我已在应用中将滑动过期设置为5分钟.如预期的那样,如果用户在5分钟后返回网站,则将用户重定向到登录页面,但是如果用户在5分钟内返回,则该用户将自动登录.如果浏览器关闭,是否可以注销用户?

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?

推荐答案

没有直接的方法来检测浏览器是否关闭,但是您当然可以检查选项卡是否已关闭.您可以按照复杂程度使用以下方式:

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:

在您的<body>标记上收听unload事件:

Listen for the unload event on your <body> tag:

<html>
  <body onunload="tellServerBrowserClosed()">
  <!--...-->

注意事项:即使您通过链接(在同一站点内)或浏览器后退按钮离开站点,也会触发. ( not a good solution )

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)

只需定期( 20-60秒间隔)从浏览器(应包含用户cookie的 )向浏览器的API发送Ajax GET请求.如果错过了2-3个信标( API调用),请清除该用户的数据.

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.

注意事项::您需要实现服务器端cronjob来处理过期的信标

Caveat: You need to implement a server side cronjob to deal with expired beacons

使用WebSocket连接(也许是 Socket.io ).这样,一旦用户关闭选项卡,连接就会关闭,您可以使用此事件清除其会话. (为了提高准确性,您可能希望跟踪同一用户的多个套接字连接,以防他们使用多于1个标签 )

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)

这篇关于.net核心cookie身份验证在浏览器上关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆