更新ClaimsPrincipal中的索赔 [英] Update claims in ClaimsPrincipal

查看:134
本文介绍了更新ClaimsPrincipal中的索赔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Adal与Azure Active Directory结合使用,并且需要通过自定义OwinMiddleware添加其他声明。
当我向该主体添加声明时,可以在当前请求中访问它们。但是,在刷新页面之后,该声明就消失了。

I am using Adal with Azure Active Directory and I need to add extra claims via custom OwinMiddleware. When I add claims to this principal, I am able to access them in the current request. But after a page refresh, the claim is gone.

我认为Owin处理了声明的序列化并将其放入cookie本身,但这似乎不是

I thought Owin handled serialization of claims and put it into a cookie itself, but this doesn't seem to be the case.

我将声明添加如下:

 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的新声明的任何想法?

Any ideas on how to persist the new claims to the cookie?

推荐答案

我已将声明添加到错误的身份。

I've added the claims to the wrong Identity. They had to be added to the identity variable instead of the 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});

这篇关于更新ClaimsPrincipal中的索赔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆