ASP.NET身份2记住我 - 用户被注销

时间:2015-01-05 23:00:58

标签: c# asp.net-mvc-5 remember-me asp.net-identity-2

我在我的MVC5应用程序中使用Identity 2.1。 我将PasswordSignInAsync的isPersistent属性设置为true以启用'记住我':

var result = await SignInManager.PasswordSignInAsync(model.Username, 
  model.Password, 
  true, 
  shouldLockout: false);

但如果我一夜之间保持登录状态,那么当我在早上刷新页面时,它会将我退出,我必须再次登录。 如何在用户手动注销之前阻止自动注销?

是否与身份使用的Cookie身份验证有关?我不太了解Startup.Auth.cs中设置的CookieAuthenticationOptions。

new CookieAuthenticationProvider
{  
   OnValidateIdentity = SecurityStampValidator
      .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
      validateInterval: TimeSpan.FromMinutes(30),
      regenerateIdentity: (manager, user)
      => user.GenerateUserIdentityAsync(manager))
}

5 个答案:

答案 0 :(得分:12)

我认为你应该阅读this article。有两种不同的时间间隔:ValidateIntervalExpireTimeSpan。在您的情况下,我认为您应该更改expireTimeSpan,而不是ValidateInterval

答案 1 :(得分:2)

similar question中有TimeSpan参数的说明。只需使用无限的cookie,如下所示:

OnValidateIdentity = SecurityStampValidator
  .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  validateInterval: TimeSpan.FromMinutes(0),
  regenerateIdentity: (manager, user)
  => user.GenerateUserIdentityAsync(manager))

这也是正常工作所必需的:

致电

await UserManager.UpdateSecurityStampAsync(userId);

之前

AuthenticationManager.SignOut(); 

答案 2 :(得分:0)

我应该写更多。这个奇怪的代码:

OnValidateIdentity = SecurityStampValidator
  .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  validateInterval: TimeSpan.FromMinutes(0),
  regenerateIdentity: (manager, user)
  => user.GenerateUserIdentityAsync(manager))

导致我的应用在1天后丢失了Cookie。我真的不知道为什么,但在排除这些代码并在我的web.config中添加一个mashine密钥之后“记住我”未来终于正常工作了。

我目前的代码是:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
   AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
   LoginPath = new PathString("/Account/Login"),
   ExpireTimeSpan = TimeSpan.FromDays(5)
});

答案 3 :(得分:0)

表单this postisPersistent参数设置身份验证会话是否在多个请求中保持不变。

答案 4 :(得分:0)

我遇到了这个问题。这是因为我的自定义UserStore没有实现IUserSecurityStampStore。

public Task<string> GetSecurityStampAsync(IdentityUser user)
{
    return Task.FromResult<string>(user.SecurityStamp);
}

没有安全标记,SecurityStampValidator没有要验证的内容,因此将用户注销。

相关问题