ASP.网络标识滑动过期设置为true不会重新发布cookie

本文关键字:true cookie 新发布 设置 标识 网络 过期 ASP | 更新日期: 2023-09-27 18:02:50

我正在使用ASP。Net身份验证来控制我的应用程序授权,我需要在指定的不活动分钟后终止用户会话,我试图通过执行以下方法来实现这一点

public void ConfigureAuth(IAppBuilder app) {
    app.CreatePerOwinContext<UserStore>(() => new UserStore());
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.UseCookieAuthentication(new CookieAuthenticationOptions {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/login"),
        LogoutPath = new PathString("/logout"),
        CookieDomain = ConfigurationManager.AppSettings["CookieDomain"],
        Provider = new CookieAuthenticationProvider {
            // Enables the application to validate the security stamp when the user logs in.
            // This is a security feature which is used when you change a password or add an external login to your account.  
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(2),
                regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)
            )
        },
        SlidingExpiration = true,
    });
}

我也试过这个方法

app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/login"),
    LogoutPath = new PathString("/logout"),
    CookieDomain = ConfigurationManager.AppSettings["CookieDomain"],
    ExpireTimeSpan = TimeSpan.FromMinutes(2),
    SlidingExpiration = true,
});

使用这些方法,用户cookie会话在2分钟后过期,无论用户是否在站点中活跃。我在文档中读到,通过设置SlidingExpiration = true, cookie将在ExpireTimeSpan中途的任何请求上重新发布。例如,如果用户登录了,然后在16分钟后发出了第二个请求,那么cookie将被重新颁发30分钟。如果用户登录了,然后在31分钟后发出了第二次请求,那么用户将被提示登录。

我不知道为什么它不工作,有什么想法吗?

ASP.网络标识滑动过期设置为true不会重新发布cookie

需要说明的是:在请求刷新之前,CookieHandler正在检查直到cookie过期的剩余时间是否小于自问题以来经过的时间(意味着它>已过期一半)。在Microsoft.AspNetCore.Authentication.Cookies的dll中。

就我个人而言,我更希望有一个选项来改变延迟的百分比。当你使用非常小的超时时间(15分钟或更短)时,对于更安全的应用程序,让用户在7分钟不活动后超时,因为cookie在他们活动的前6分钟内从未刷新,这是相当烦人的。也许可以添加一个选项,对一个常量使用剩余时间跨度检查。例如,当cookie的剩余时间少于{TimeSpan}时发出刷新请求。

private void CheckForRefresh(AuthenticationTicket ticket)
{
  DateTimeOffset utcNow = this.get_Clock().get_UtcNow();
  DateTimeOffset? issuedUtc = ticket.get_Properties().get_IssuedUtc();
  DateTimeOffset? expiresUtc = ticket.get_Properties().get_ExpiresUtc();
  bool? allowRefresh = ticket.get_Properties().get_AllowRefresh();
  bool flag = !allowRefresh.HasValue || allowRefresh.GetValueOrDefault();
  if (((!issuedUtc.HasValue || !expiresUtc.HasValue ? 0 : (this.get_Options().SlidingExpiration ? 1 : 0)) & (flag ? 1 : 0)) == 0)
    return;
  TimeSpan timeSpan = utcNow.Subtract(issuedUtc.Value);
  if (!(expiresUtc.Value.Subtract(utcNow) < timeSpan))
    return;
  this.RequestRefresh(ticket);
}

我怀疑问题是刷新行为被抑制,尽管SlidingExpiration为真。查看Katana源代码,CookieAuthenticationHandler类,AuthenticateCoreAsync()方法,我们看到:

bool? allowRefresh = ticket.Properties.AllowRefresh;
if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration
    && (!allowRefresh.HasValue || allowRefresh.Value))
{
    TimeSpan timeElapsed = currentUtc.Subtract(issuedUtc.Value);
    TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc);
    if (timeRemaining < timeElapsed)
    {
    _shouldRenew = true;
    _renewIssuedUtc = currentUtc;
    TimeSpan timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value);
    _renewExpiresUtc = currentUtc.Add(timeSpan);
    }
}

。刷新仅在ticket.Properties.AllowRefresh为null或true时发生,并且根据您使用的中间件可能将其设置为false。例如,在OpenIdConnectAuthenticationHandler和WsFederationAuthenticationHandler中,我们有这个…

private ClaimsPrincipal ValidateToken(...)
{
    ...
    if (Options.UseTokenLifetime)
    {
        // Override any session persistence to match the token lifetime.
        DateTime issued = jwt.ValidFrom;
        if (issued != DateTime.MinValue)
        {
            properties.IssuedUtc = issued.ToUniversalTime();
        }
        DateTime expires = jwt.ValidTo;
        if (expires != DateTime.MinValue)
        {
            properties.ExpiresUtc = expires.ToUniversalTime();
        }
        properties.AllowRefresh = false;
    }
}
注意UseTokenLifetime默认为true。因此,默认行为是使用我们从IdP服务器获得的身份验证令牌的过期时间,并在达到该过期时间时结束会话,无论用户是否处于活动状态。