更新 ClaimsPrincipal 中的声明

Update claims in ClaimsPrincipal

我正在将 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 的新声明有什么想法吗?

我向错误的身份添加了声明。必须将它们添加到标识变量而不是 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});