Blazor 级联 AuthorizeView 策略不起作用

Blazor cascading AuthorizeView Policy not working

我正在开发一个新项目,该项目将针对用户可以和不可以使用 Identity Server 4 制定一些深入的政策access/see。

我正在尝试将 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");
                });

当我的应用程序运行时,菜单中的 none 项会显示,但不受 AuthorizeView 保护的主页和声明项除外。

该问题是由于目前不支持 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;
        }
    }
}

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

builder.Services.AddOidcAuthentication(options =>
        {
            builder.Configuration.Bind("oidc", options.ProviderOptions);
        })
        .AddAccountClaimsPrincipalFactory<ArrayClaimsPrincipalFactory<RemoteUserAccount>>();

在了解了史蒂夫的问题后,我做了以下解决方案。 对关注 Cris Sainty 的人有用 documentation

我更新了我的方法来解析来自 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;
}