如何在OWIN CookieAuthenticationProvider中更新声明?

4
在使用OWIN管道的ASP.NET应用程序中,我试图使用cookie身份验证并覆盖CookieAuthenticationProvider.ValidateIdentity来执行类似以下操作的功能:
public override Task ValidateIdentity(CookieValidateIdentityContext context) {
    Claim simpleClaim = context.Identity.FindFirst("SIMPLECOUNT");
    if (simpleClaim != null) {
        Trace.WriteLine($"SIMPLECOUNT: {simpleClaim.Value}");
        if (context.Identity.TryRemoveClaim(simpleClaim)) {
            var newIdentity = new ClaimsIdentity(context.Identity);
            int newcount = 1 + int.Parse(simpleClaim.Value);
            newIdentity.AddClaim(new Claim("SIMPLECOUNT", newcount.ToString()));
            context.ReplaceIdentity(newIdentity);
        }               
    }

    return Task.FromResult<object>(null);
}

实际上,我正在更新其他索赔,并且只是偶尔这样做。但是这凸显了主要的混淆。我可以调用context.RejectIdentity()或者我可以调用context.ReplaceIdentity()。假设如果我调用"reject", 旧的ClaimsIdentity将被删除。因此,如果我在抹掉旧索赔值后反复替换ClaimsIdentity,并添加带有递增值的索赔,我期望永远不会再次看到旧值。
但实际情况并非如此。同样的值一直出现。通过调整cookie超时设置,我可以看到一个递增的声明值最终会显示出来,因为由于滑动过期而替换了cookie。新值在哪里被"排队",以便最终进行更新呢?
至于反复出现的旧值,这是浏览器的cookie重新断言吗?我不想登出用户以更新索赔-事实上,我严肃地仅使用索赔作为存储,因为我不知道在这种情况下(而不是控制器方法)还能使用什么。有更好的方法吗?最终我试图做的是将cookie到期与写入新cookie的更新API令牌同步。
1个回答

1

我知道这可能有点晚了,但我发现如果再次登录用户,则旧的声明将被新的声明替换。因此,您的情况将如下所示。

public override Task ValidateIdentity(CookieValidateIdentityContext context) {
    Claim simpleClaim = context.Identity.FindFirst("SIMPLECOUNT");
    if (simpleClaim != null) {
        Trace.WriteLine($"SIMPLECOUNT: {simpleClaim.Value}");
        if (context.Identity.TryRemoveClaim(simpleClaim)) {
            var newIdentity = new ClaimsIdentity(context.Identity);
            int newcount = 1 + int.Parse(simpleClaim.Value);
            newIdentity.AddClaim(new Claim("SIMPLECOUNT", newcount.ToString()));

            context.Request.Context.Authentication.SignIn(newIdentity);
        }               
    }

    return Task.FromResult<object>(null);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接