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

查看:27
本文介绍了浏览器关闭时的 .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:

监听 标签上的 unload 事件:

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)

只需定期(20-60 秒间隔)从浏览器(应该有用户的 cookie)向 API 发送 Ajax GET 请求em>).当 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.

警告:你需要实现一个服务器端的定时任务来处理过期的信标

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天全站免登陆