簡體   English   中英

ASP.NET Identity 2 記住我 - 用戶正在注銷

[英]ASP.NET Identity 2 Remember Me - User Is Being Logged Out

我在我的 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))
}

我認為你應該閱讀這篇文章 有兩種不同的時間間隔: ValidateIntervalExpireTimeSpan 在您的情況下,我認為您應該更改expireTimeSpan ,而不是ValidateInterval

類似問題中有對TimeSpan參數的解釋。 只需使用無限 cookie,如下所示:

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

這也是它正常工作所必需的:

稱呼

await UserManager.UpdateSecurityStampAsync(userId);

AuthenticationManager.SignOut(); 

這篇文章中isPersistent參數設置身份驗證會話是否跨多個請求持久化。

我有這個問題。 這是因為我的自定義 UserStore 沒有實現 IUserSecurityStampStore。

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

如果沒有安全標記,SecurityStampValidator 就沒有什么可驗證的,因此注銷用戶。

我應該多寫點。 這個奇怪的代碼:

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)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM