更新ClaimsPrincipal中的声明

20

我正在使用Adal与Azure Active Directory,需要通过自定义OwinMiddleware添加额外的声明。

当我向此主体添加声明时,我可以在当前请求中访问它们。但是在页面刷新后,该声明就会消失。

我认为Owin处理声明的序列化并将其放入cookie中,但事实并非如此。

我按以下方式添加声明:

 var claimsIdentity = (ClaimsIdentity) ClaimsPrincipal.Current.Identity;
        if (!claimsIdentity.IsAuthenticated) return;

        var identity = new ClaimsIdentity(claimsIdentity);

        var currentTenantClaim = GetTenantClaim();

        if (currentTenantClaim != null)
            claimsIdentity.RemoveClaim(currentTenantClaim);

        claimsIdentity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));

        context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
            (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});
任何有关如何将新的索赔记录到cookie中的想法?
2个回答

20

我把声明添加到了错误的身份上。它们应该添加到identity变量而不是claimsIdentity上。

工作代码:

        var claimsIdentity = (ClaimsIdentity) context.Authentication.User.Identity;
        if (!claimsIdentity.IsAuthenticated) return;

        var identity = new ClaimsIdentity(claimsIdentity);

        var currentTenantClaim = GetTenantClaim(identity);

        if (currentTenantClaim != null)
            identity.RemoveClaim(currentTenantClaim);

        identity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));

        context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
            (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});

这正是我需要做的。你能分享完整的代码吗?谢谢。 - Sam
3
你的代码示例中第一行中的 context 对象是什么类型? - joym8

4
这是我在使用.NET 6时成功的方法:
var identity = (ClaimsIdentity)Request.HttpContext.User.Identity;
identity.AddClaim(new Claim("ClaimName", "ClaimValue"));
    

如果我想验证这个身份的声明,我会这样做

var Claims = User.Claims;

希望这可以帮助到某些人


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