【问题标题】:Asp.net MVC when to reload claims when lostAsp.net MVC 丢失时何时重新加载声明
【发布时间】:2016-01-06 08:14:07
【问题描述】:

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

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

【问题讨论】:

  • 您是否使用状态服务器来处理会话状态?
  • 我没有处理任何会话状态。
  • 好的。在您的服务器上启用 Asp.net 会话状态服务并配置您的应用程序以使用它可能值得一看。如果不使用会话状态服务器或数据库来存储会话状态,它可能不会持续超过当您的应用程序在不活动后定期回收时。我有点困惑,为什么你会失去索赔而不是登录:/,我原以为是全有或全无
  • 好的,谢谢您的信息。我不知道它是怎么发生的。我会更新描述。
  • @Coulton 这是 Asp.Net Identity 技巧,与会话无关,因为这里根本不使用会话。

标签: asp.net asp.net-mvc claims-based-identity asp.net-identity-2


【解决方案1】:

你正在面对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&lt;ApplicationUser&gt; manager) 方法以包含您的声明。并且不要在其他任何地方添加声明。

【讨论】:

  • 正确,谢谢。无论如何,我这边的一个小问题是我在一个单独的类项目中有ApplicationUser,我的所有其他项目都在使用它,所以添加它会导致循环引用错误。我可以在 regenerateIdentity 上使用或如何使用 spearate GenerateUserIdentityAsync 吗?
  • 是的,您可以创建一个新方法来创建身份并将其作为函数参数传递给SecurityStampValidator。您可以为您正在使用的每个项目使用其中的一些。
  • 我使用了来自manager 的新CreateIdentityAsync。我已经登录的用户(自从索赔丢失后我还没有退出),他们的索赔没有被重新加载。
  • 尝试清除 cookie 并再次登录。出于测试目的,您可以将validateInterval 减少到几秒钟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 2022-06-30
相关资源
最近更新 更多