4

我正在开发一个新项目,该项目将对 Identity Server 4 的用户可以访问/查看的内容有一些深入的策略。

我正在尝试将 AuthorizeView 与策略一起使用来隐藏导航中的选项,但是视图是级联的,这意味着我有这样的东西:

<MatNavMenu>
<MatNavItem Href="/home" Title="Home"><MatIcon Icon="@MatIconNames.Home"></MatIcon>&nbsp; Home</MatNavItem>
<MatNavItem Href="/claims" Title="Claims"><MatIcon Icon="@MatIconNames.Vpn_key"></MatIcon>&nbsp; Claims</MatNavItem>
<AuthorizeView Policy="@PolicyNames.IdentitySystemAccess">
    <Authorized>
        <AuthorizeView Policy="@PolicyNames.AccessManagement">
            <Authorized>
                <MatNavSubMenu @bind-Expanded="@_accessSubMenuState">
                    <MatNavSubMenuHeader>
                        <MatNavItem AllowSelection="false">&nbsp; Access Management</MatNavItem>
                    </MatNavSubMenuHeader>
                    <MatNavSubMenuList>
                        <AuthorizeView Policy="@PolicyNames.User">
                            <Authorized>
                                <MatNavItem Href="users" Title="users"><MatIcon Icon="@MatIconNames.People"></MatIcon>&nbsp; Users</MatNavItem>
                            </Authorized>                               
                        </AuthorizeView>
                        <AuthorizeView Policy="@PolicyNames.Role">
                            <Authorized>
                                <MatNavItem Href="roles" Title="roles"><MatIcon Icon="@MatIconNames.Group"></MatIcon>&nbsp; Roles</MatNavItem>
                            </Authorized>
                        </AuthorizeView>
                    </MatNavSubMenuList>
                </MatNavSubMenu>
            </Authorized>
        </AuthorizeView>
    </Authorized>
</AuthorizeView>

我检查了用户登录后是否存在满足定义的策略所需的声明,但由于某种原因 AuthorizeView 不起作用。

我已更新我的 App.Razor 以使用 AuthorizeRouteView。关于为什么会发生这种情况的任何想法?

注意:我正在使用分配给角色的声明,但这些声明是动态的,我不能在我的策略中使用 policy.RequireRole("my-role"),因此使用:

options.AddPolicy(PolicyNames.User, b =>
                {
                    b.RequireAuthenticatedUser();
                    b.RequireClaim(CustomClaimTypes.User, "c", "r", "u", "d");
                });

当我的应用程序运行时,菜单中的任何项目都不会显示,除了不受 AuthorizeView 保护的主页和声明项目。

4

2 回答 2

3

该问题是由于当前不支持 Blazor 读取作为数组发送的声明。

例如用户:["c","r","u","d"]

无法读取。

要纠正这个问题,您需要添加ClaimsPrincipalFactory

例如

using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication.Internal;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;

namespace YourNameSpace
{
    public class ArrayClaimsPrincipalFactory<TAccount> : AccountClaimsPrincipalFactory<TAccount> where TAccount : RemoteUserAccount
    {
        public ArrayClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
        : base(accessor)
        { }


        // when a user belongs to multiple roles, IS4 returns a single claim with a serialised array of values
        // this class improves the original factory by deserializing the claims in the correct way
        public async override ValueTask<ClaimsPrincipal> CreateUserAsync(TAccount account, RemoteAuthenticationUserOptions options)
        {
            var user = await base.CreateUserAsync(account, options);

            var claimsIdentity = (ClaimsIdentity)user.Identity;

            if (account != null)
            {
                foreach (var kvp in account.AdditionalProperties)
                {
                    var name = kvp.Key;
                    var value = kvp.Value;
                    if (value != null &&
                        (value is JsonElement element && element.ValueKind == JsonValueKind.Array))
                    {
                        claimsIdentity.RemoveClaim(claimsIdentity.FindFirst(kvp.Key));

                        var claims = element.EnumerateArray()
                            .Select(x => new Claim(kvp.Key, x.ToString()));

                        claimsIdentity.AddClaims(claims);
                    }
                }
            }

            return user;
        }
    }
}

然后在您的程序/启动中注册它(取决于您是否使用 .core 托管),如下所示:

builder.Services.AddOidcAuthentication(options =>
        {
            builder.Configuration.Bind("oidc", options.ProviderOptions);
        })
        .AddAccountClaimsPrincipalFactory<ArrayClaimsPrincipalFactory<RemoteUserAccount>>();
于 2020-12-24T15:18:59.470 回答
0

在了解史蒂夫的问题后,我做了以下解决方案。对于那些遵循 Cris Sainty文档的人很有用

我更新了我的方法来解析来自 jwt 的声明以分离所有声明的数组!

private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
    var claims = new List<Claim>();
    var payload = jwt.Split('.')[1];
    var jsonBytes = ParseBase64WithoutPadding(payload);
    var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);

    keyValuePairs.TryGetValue(ClaimTypes.Role, out object roles);

    if (roles != null)
    {
        if (roles.ToString().Trim().StartsWith("["))
        {
            var parsedRoles = JsonSerializer.Deserialize<string[]>(roles.ToString());
            foreach (var parsedRole in parsedRoles)
            {
               claims.Add(new Claim(ClaimTypes.Role, parsedRole));
            }
        }
        else
        {
            claims.Add(new Claim(ClaimTypes.Role, roles.ToString()));
        }
        keyValuePairs.Remove(ClaimTypes.Role);
    }
    claims.AddRange(keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())));
    for (int i = 0; i < claims.Count; i++)
    {
        var name = claims[i].Type;
        var value = claims[i].Value;
        if (value != null && value.StartsWith("["))
        {
            var array = JsonSerializer.Deserialize<List<string>>(value);
            claims.Remove(claims[i]);
            foreach (var item in array)
            {
                claims.Add(new Claim(name, item));
            }
        }
    }
    return claims;
}
于 2020-12-24T17:40:47.587 回答