C# 如何在注销前将ASP.NET身份声明保留在cookie上?

C# 如何在注销前将ASP.NET身份声明保留在cookie上?,c#,cookies,asp.net-mvc-5,asp.net-identity-2,C#,Cookies,Asp.net Mvc 5,Asp.net Identity 2,我正在制作一个使用Identity的ASP.NETMVC5应用程序。身份验证的一部分包括将声明存储在cookie中,而不将其保存到数据库,因为该声明必须持续到用户注销为止。此声明在注销后添加到用户标识中,用户可以在登录时随时更改声明的值。为此,我使用以下代码: var AuthenticationManager = HttpContext.GetOwinContext().Authentication; var Identity = User.Identity as ClaimsIdentity

我正在制作一个使用Identity的ASP.NETMVC5应用程序。身份验证的一部分包括将声明存储在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 });

这在一段时间内效果很好。。。但在用户登录后大约十分钟,索赔就消失了!如何使声明持续到注销?

您的问题是在
启动中配置的
SecurityStampValidator
正在擦除存储在cookie中的自定义声明

您需要在
ConfigureAuth(IAppBuilder应用程序)
中查看这段代码:

OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(10),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器)),
特别是传递的函数
user.GenerateUserIdentityAsync(manager))


您需要修改此方法
ApplicationUser.GenerateUserIdentityAsync
,以便在cookie中还原自定义声明(如果它们存在于cookie中)。

存储在cookie中可能不是一个好方法idea@yenkay你能把你修改过的代码贴出来吗?我也有同样的问题。但我不明白我应该做些什么来让它工作。@yaza,他们的意思是。。。。。由于安全特性,您可能必须为声明设置缓存层或DB持久层,因为如果您设置为验证SecurityStamp(这将引导多次登录)。。。。它将每x时间(在他给出的示例中,是10分钟)擦除一次索赔。
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
    validateInterval: TimeSpan.FromMinutes(10),
    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),