代码之家  ›  专栏  ›  技术社区  ›  Ruchan

天冬氨酸。net MVC丢失时重新加载索赔

  •  3
  • Ruchan  · 技术社区  · 9 年前

    我在登录时添加了一些自定义声明。

    private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            var accesses = _roleAccessRepository.GetAssignedAccess(roleId);
            foreach (var access in accesses)
            {
               identity.AddClaim(new Claim("AccessCode", access));
            }
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }
    

    它们工作得很好,直到我最近发现,在某些不活动之后,我假设超过30分钟,这些声明就消失了。但是,用户仍在登录。

    当用户仍然登录时,如何重新加载这些声明?

    更新:它是如何发生的。

    我登录了一个用户,大约30分钟后再次打开它,然后注销。它没有被注销,而是刷新了我的页面,没有任何声明。

    1 回复  |  直到 9 年前
        1
  •  4
  •   trailmax    9 年前

    你面对的是 SecurityStampValidator 在行动中。在VS2013/VS2015的标准MVC5模板中,有一个文件 App_Start\Startup.Auth.cs 它有以下几行:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        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(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    }); 
    

    你需要看看 SecurityStampValidator.OnValidateIdentity -此方法每30分钟重新生成一次cookie(在默认配置中)。而且它不保留在 user.GenerateUserIdentityAsync(manager) .

    所以你需要找到 ApplicationUser 类并修改 GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 方法来包括您的索赔。不要在其他地方添加索赔。