我有一个名为组
的声明。当我设置 TokenValidationParameters
时,我将 RoleClaimType
设置为 groups
。
当声明通过时,groups
声明的值如下:
"something,some other thing,more things,other other things"
但是当我打电话时:
User.IsInRole("some other thing");
结果是False
。
IsInRole
在该声明中期望什么?
意思是它需要分号分隔、逗号分隔(这似乎不起作用)、空格分隔还是单个值(不确定它如何成为“in”检查是否是单个值。)
最佳答案
IsInRole
希望声明包含您要查找的值。
这就是为什么它在你的情况下不起作用。
您可以做的是像这样进行声明转换:
public class AzureAdGroupsSplitClaimTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identities = principal.Identities;
if (identities == null)
{
return Task.FromResult(principal);
}
var result = new List<ClaimsIdentity>();
var groupsClaimSplit = false;
// Iterate each identity the user may have, make sure to keep all of them
foreach (var identity in identities)
{
var groupClaims = identity.FindAll("groups").ToList();
if (groupClaims.Count != 1 || !groupClaims[0].Value.Contains(','))
{
// groupClaims.Count == 0: Identity does not have groups
// groupClaims.Count > 1: Identity has more than one groups claim, already split
// The only groups claim does not contain a comma: Identity has one group, no need to split
result.Add(identity);
continue;
}
var claim = groupClaims[0];
var groups = claim.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
var claims = groups.Select(s => new Claim("groups", s));
var updatedIdentity = new ClaimsIdentity(identity, claims);
result.Add(updatedIdentity);
groupsClaimSplit = true;
}
// Nothing was done to the original identities, may as well just return the original principal
if (!groupsClaimSplit)
{
return Task.FromResult(principal);
}
return Task.FromResult(new ClaimsPrincipal(result));
}
}
然后将其注册到服务集合中:
services.AddSingleton<IClaimsTransformation, AzureAdGroupsSplitClaimTransformation>();
现在您应该仅使用单个值为用户获取其他组声明。
然后你的角色检查应该起作用了。
虽然为此目的使用 IsInRole 有点奇怪,
您还可以使用User.HasClaim("groups", "your-group-id")
。
关于c# - `ClaimsPrincipal.IsInRole` 在声明中期望什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61377149/