c# - `ClaimsPrincipal.IsInRole` 在声明中期望什么?

标签 c# asp.net-core asp.net-core-3.1 claims

我有一个名为的声明。当我设置 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/

相关文章:

c# - System.TimeoutException : A timeout occured after 30000ms selecting a server using CompositeServerSelector

c# - 在输出中出现错误消息后重新启动 while 循环

c# - 冗余控制流跳转语句及跳转语句的执行

.net - JetBrains dotCover 代码覆盖率分析失败,错误为 "Invalid stream header"

c# - 将 ArrayPool 对象提供给 JsonOutputFormatter 构造函数

iis-express - 为什么 IIS Express 锁定文件停止在 ASP.Net Core 中构建、重建和清理?

c# - 集成测试 .NET Core 3 Worker

c# - 将 asp.net core 2.2 项目迁移到版本 3.1 后的分析器异常

C#线程似乎启动了多次

c# - 使用 .NET Core 2.1 的托管 C++