ASP.NET Identity 2.0会阻止身份验证Cookie过期

时间:2016-06-14 07:13:23

标签: jquery asp.net asp.net-mvc cookies asp.net-identity

我正在开发一个应用程序( ASP.NET MVC 5 ),我想阻止特定页面上的auth cookie过期(这是一个巨大的形式,需要一些时间才能完全填写)。我所拥有的是:

Startup.cs

中的ASP.NET身份配置
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
            validateInterval: TimeSpan.FromMinutes(15),
            regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
            getUserIdCallback: (id) => Guid.Parse(id.GetUserId()))
    },
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(30)
});
控制器中的

SignIn 方法实现

AuthenticationManager.SignIn(new AuthenticationProperties()
{
    AllowRefresh = true,
    IsPersistent = isPersistent,
    ExpiresUtc = TimeSpan.FromMinutes(30)
}, identity);

jQuery 方法实现在特定页面上,每10分钟发布一次到服务器。

(function ($) {

    function keepSessionAlive() {
        $.post("/Resources/KeepSessionAlive");
    }

    // 10 minutes
    setInterval(keepSessionAlive, 60 * 1000 * 10);

})(jQuery);
Controller中的

KeepSessionAlive 实现

//
// POST: /Resources/KeepSessionAlive/
[HttpPost]
public JsonResult KeepSessionAlive()
{
    if (HttpContext.Session != null)
        HttpContext.Session["KeepSessionAlive"] = DateTime.Now;
    return Json($"Last refresh {DateTime.Now.ToString("O")}");
}

问题: 当我导航到特定页面时,我可以看到以下帖子请求:

  1. / Resources / KeepSessionAlive - 200 OK
  2. / Resources / KeepSessionAlive - 200 OK
  3. / Resources / KeepSessionAlive - 401 Unauthorized
  4. 但是30分钟后我得到401未经授权。我做错了什么?

    顺便说一下。 CookieAuthenticationOptions.ExpireTimeSpan AuthenticationProperties.ExpiresUtc 之间有什么区别。它一定是一样的吗?如果我将它们设置为不同的值,它的行为如何?谢谢你的澄清。

    //编辑:

    我发现Cookie会在15分钟后过期,等于validateInterval: TimeSpan.FromMinutes(15),但我认为它不会影响Cookie过期,因为this is a security feature which is used when you change a password or add an external login to your account

1 个答案:

答案 0 :(得分:1)

我不明白,但是当我将CookieAuthenticationOptions.ExpireTimeSpanAuthenticationProperties.ExpiresUtc设置为相同的值(30分钟)时,它就开始工作了。< / p>

最终源代码:

<强> Startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(30),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
            getUserIdCallback: (id) => Guid.Parse(id.GetUserId()))
    }
});

<强>登入

AuthenticationManager.SignIn(new AuthenticationProperties() { 
  IsPersistent = isPersistent }, identity);

<强>的jQuery

function keepSessionAlive() {
    $.ajax({
        type: "POST",
        cache: false,
        url: "/Resources/KeepSessionAlive",
        success: function (result) {
            console.debug("keepSessionAlive response [" + result + "]");
            window.setTimeout(keepSessionAlive, 60 * 1000 * 15); // 15 minutes
        }
    });
}
keepSessionAlive();