我正在尝试在我自己的
TransformAsync
实现中使用 IClaimsTransformation
方法来操作我的网络应用程序中的声明。
微软文档中的示例代码如下所示:
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
public class MyClaimsTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity();
var claimType = "myNewClaim";
if (!principal.HasClaim(claim => claim.Type == claimType))
{
claimsIdentity.AddClaim(new Claim(claimType, "myClaimValue"));
}
principal.AddIdentity(claimsIdentity);
return Task.FromResult(principal);
}
}
我明白,正如文档所述,“此方法可能会被多次调用”,因此在我的版本中,如示例所示,我确保在添加每个声明之前检查它是否存在。
我似乎最终遇到了调用此方法并且我的
ClaimsPrincipal
有多个 ClaimsIdentity
的情况。我试图通过在方法的开头添加这一行来解决它(基于这个答案):
ClaimsIdentity claimsIdentity = principal.Identity != null ? (ClaimsIdentity)principal.Identity : new ClaimsIdentity();
不过,我真正想知道的是,为什么 Microsoft 的示例代码每次创建新的
ClaimsIdentity
并将其添加到 ClaimsPrincipal
时都是正确的。看起来很直观,如果重复调用该方法,这将导致 ClaimsPrincipal
具有多个身份,但显然情况并非如此(在这种情况下,为什么?),或者 Microsoft 的示例有缺陷。为什么它不尝试将新声明添加到现有ClaimsIdentity
,而不是每次创建一个新声明?
从直觉上看,这会导致 ClaimsPrincipal 多重身份
在asp.net core中,
ClaimsPrincipal
代表User,ClaimsIdentity
代表可以提供User信息的东西,比如用户的信用卡/google账户/护照.....,ClaimsPrincipal
可以保存多个ClaimsIdentity
,
并且可以创建一个新的 ClaimsIdentity
来保存不应存在于其他 ClaimsIdentity
中的自定义声明