【问题标题】:ASP.NET Core 2.2 Logoff user when browser tab is closed - IsPersistent has no effect关闭浏览器选项卡时 ASP.NET Core 2.2 注销用户 - IsPersistent 无效
【发布时间】:2019-09-21 13:17:58
【问题描述】:

我知道这个问题似乎已经被问过了,但是这与 ASP.NET Core 而不是 ASP.NET 5 有关。

当用户关闭浏览器选项卡时,我试图让用户注销;我正在 MacOS 上使用 Chrome 和 Safari 进行测试。

目前,当我登录用户,并且浏览器选项卡关闭并重新打开时,用户仍然处于登录状态。

当我登录用户时,我将AuthenticationProperties IsPersistent 设置为false。然而,在 Chrome 和 Safari 上关闭浏览器选项卡时,用户仍保持登录状态。 (浏览器没有关闭,只有标签页)。

        Task task = HttpContext.SignInAsync(principal, 
           new AuthenticationProperties
           {
              IsPersistent = false
           });             
        await task;

根据文档:persistent-cookies

“您可能希望 cookie 在浏览器会话中持续存在”

在上面的例子中,我将 IsPersistent 设置为 false,并且我假设 cookie 不应在会话中存活。

据我了解,浏览器不会关闭会话,服务器会关闭会话,并将其设置为 10 秒以下。

但通过如下测试,我无法让用户退出。

  1. 登录用户
  2. 确认用户已登录
  3. 关闭浏览器选项卡,(不关闭浏览器)
  4. 等待超过 10 秒
  5. 打开浏览器选项卡并确保用户未登录。失败

这可能无关紧要... Starup.cs 有这个:

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            // Make the session cookie essential
            options.Cookie.IsEssential = true;

        });

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/auth/login";
            options.AccessDeniedPath = "/auth/accessdenied";
        });

【问题讨论】:

  • asp.net 5下是否有答案。因为我感觉它会是相同的答案。
  • 我认为这无关紧要。我会在问题中添加更多文字。
  • 听起来你需要在会​​话变量中存储用户名之类的东西。然后在每个控件中检查该值。如果会话已过期,则路由到登录页面

标签: c# asp.net-core


【解决方案1】:

会话 Cookie 和身份验证 Cookie 是两个独立的 Cookie, 因此options.IdleTimeout = TimeSpan.FromSeconds(10); 对身份验证 cookie 没有影响。

通过如下设置ExpireTimeSpan 身份验证cookie 选项,将导致用户在浏览器关闭或不活动超过10 秒时注销。此外,SlidingExpiration 将通过在旧的 cookie 过期之前发出新的 cookie 来实现不注销用户的预期效果,如果在过期时间之前处于活动状态。

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/auth/login";
            options.AccessDeniedPath = "/auth/accessdenied";
            options.Cookie.IsEssential = true;
            options.SlidingExpiration = true; // here 1
            options.ExpireTimeSpan = TimeSpan.FromSeconds(10);// here 2
        });

IsPersistent 属性设置为 true 时,不会影响 cookie 过期时间。例如它不会使 cookie 不会过期。 IsPersistent 是在browsernot the tab 关闭后存活下来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2017-03-04
    • 2014-07-01
    • 2012-08-19
    • 2020-10-23
    相关资源
    最近更新 更多