【问题标题】:How do I persist a ASP.NET Identity Claim on a cookie until logout?如何在 cookie 上保留 ASP.NET 身份声明直到注销?
【发布时间】:2017-10-19 16:46:07
【问题描述】:

我正在制作一个使用 Identity 的 ASP.NET MVC 5 应用程序。身份验证的一部分包括将声明存储在 cookie 中,而不将其保存到数据库中,因为该声明只能持续到用户注销。此声明在注销后添加到用户身份中,并且用户可以在登录时随时更改声明的值。为此,我使用以下代码:

var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
var Identity = User.Identity as ClaimsIdentity;
if (Identity.HasClaim(c => c.Type == "custom"))
{
    Identity.RemoveClaim(Identity.FindFirst("custom"));
}
Identity.AddClaim(new Claim("custom", "value", ClaimValueTypes.Integer32));
AuthenticationManager.AuthenticationResponseGrant =
            new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });

这在一段时间内可以正常工作......但在用户登录后大约十分钟,声明就消失了!如何使声明持续到注销?

【问题讨论】:

  • 存储在 cookie 中可能不是一个好主意

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


【解决方案1】:

您的问题是Startup.Auth.cs 中配置的SecurityStampValidator 正在清除您存储在cookie 中的自定义声明。

你需要查看ConfigureAuth(IAppBuilder app)中的这段代码:

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

特别是函数通过user.GenerateUserIdentityAsync(manager))

您需要修改此方法 ApplicationUser.GenerateUserIdentityAsync 以恢复您的自定义声明,如果它们存在于 cookie 中。

【讨论】:

  • @yenkay 您能否发布您更改的代码以使其正常工作?我也有同样的问题。但我不明白我应该改变什么才能让它工作。
  • @yaza,他们的意思是......由于安全功能,您可能必须为声明设置一个缓存层或数据库持久层,因为如果您设置为验证 SecurityStamp (它会引导多次登录)....它将每隔 x 时间清除一次声明(在他给出的示例中,它是 10 分钟)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 2021-03-29
  • 2017-06-17
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多