Asp.net MVC 何时在丢失时重新加载声明

Asp.net MVC when to reload claims when lost

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

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 分钟后再次打开它,然后注销了。它没有注销,而是刷新了我的页面,没有声明。

你正在面对 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 class 并修改 GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 方法以包含您的声明。并且不要在其他任何地方添加声明。