本文介绍了在ClaimsPrincipal中添加多个身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多类似以下代码的代码,用于创建新的ClaimsIdentity和ClaimsPrincipal

I see a lot of code like the following to create a new ClaimsIdentity and ClaimsPrincipal

var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, "Me"),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.Role, "Admin")
};

var id = new ClaimsIdentity(claims, "Forms");
var principal = new ClaimsPrincipal(id);

这很简单,网络上有很多有关如何执行此操作的示例.我想做的是没有找到太多文档,是关于如何在ClaimsPrincipal中具有多个标识.ClaimsPrincipal的定义如下所示,因此很明显它支持多种身份.

This is straightforward and there are lots of examples on the web about how to do this. What I would like to do and am not finding much documentation about is how to have multiple identities within ClaimsPrincipal. ClaimsPrincipal is defined like the following so clearly it supports multiple identities.

public class ClaimsPrincipal : IPrincipal
{
  public virtual IEnumerable<ClaimsIdentity> Identities { get; }
  ...
}

我认为上述声明varPrincipal = new ClaimsPrincipal(id)的方法还不够,因为我需要能够向可能已经具有身份的ClaimsPrincipal添加身份.那么,如果您已经在ClaimsPrincipal中拥有一个身份并声明一个ClaimsPrincipal的新实例,该怎么办?您现在是否有两个具有不同标识的ClaimsPrincipal实例?我的直觉是这种情况,所以我需要检查当前ClaimsPrincipal的存在并像这样添加它:

I am thinking that the above approach of declaring var principal = new ClaimsPrincipal(id) is not sufficient because I need to be able to add an identity to a ClaimsPrincipal that may already have an identity. So what happens if you already have an identity in ClaimsPrincipal and declare a new instance of ClaimsPrincipal? Do you now have two instances of ClaimsPrincipal with different identities? My hunch is that is the case, so instead I would need to check for the existence of the current ClaimsPrincipal and add to it like so:

ClaimsPrincipal principal;
if(System.Security.Claims.ClaimsPrincipal.Current != null)
{
   principal = System.Security.Claims.ClaimsPrincipal.Current;
   principal.AddIdentity(id)

}
else
{
   principal = new ClaimsPrincipal(id);
}

我在这里正确吗?当ClaimsPrincipal中存在多个身份时,有人可以提供深入了解的信息吗?如果我走的路不正确,您能否提出建议,说明如何在ClaimsPrincipal中使用多个身份?

Am I on the right track here? Can anybody provide insight into what goes on under the hood when there are multiple identities in ClaimsPrincipal, If I am not on the right track can you offer suggestions on how I might go about using multiple identities within ClaimsPrincipal?

推荐答案

有一个构造函数,它将为您完成:

There is a constructor, which will do it for you:

public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities)

但是,其语义是不确定的.到目前为止,Microsoft尚未使用过它,而且我从未能够将其序列化为可互操作的SAML令牌……我不确定SesAM会如何使用它.

However, the semantics of this are undefined. Microsoft hasn't used it so far and I was never able to serialize it into an interoperable SAML token...... I am not sure what SesAM will do with it.

这篇关于在ClaimsPrincipal中添加多个身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 22:47