为 Blazor WebAssembly 项目创建声明

Create claims for a Blazor WebAssembly project

我使用默认的 Blazor WebAssembly 模板通过“个人用户帐户选项”创建项目,我尝试在用户登录并从 Blazor 客户端访问它时创建自定义声明,但我没有成功让它发挥作用。

我知道我必须为 Blazor 客户端项目创建一个自定义身份验证状态提供程序,但在尝试让它工作几个小时后,我还没有找到解决我的问题的方法。

有人可以给我一些实现方法吗?

Program.cs

builder.Services.AddApiAuthorization()
    .AddAccountClaimsPrincipalFactory<CustomAccountClaimsPrincipalFactory>();

CustomAccountClaimsPrincipalFactory.cs

public class CustomAccountClaimsPrincipalFactory
    : AccountClaimsPrincipalFactory<RemoteUserAccount>
{
    private const string Planet = "planet";

    public CustomAccountClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
        : base(accessor) { }

    public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
        RemoteUserAccount account,
        RemoteAuthenticationUserOptions options)
    {
        var user = await base.CreateUserAsync(account, options);

        if (user.Identity.IsAuthenticated)
        {
            var identity = (ClaimsIdentity)user.Identity;
            var claims = identity.Claims.Where(a => a.Type == Planet);
            if (!claims.Any())
            {
                identity.AddClaim(new Claim(Planet, "mars"));
            }
        }
        return user;

    }

}


ClaimDisplay.razor

@using System.Linq
@using System.Threading.Tasks
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Authorization

@ClaimType: @Claim
@code {
    [Inject]
    AuthenticationStateProvider AuthenticationStateProvider { get; set; }

    [Parameter]
    public string ClaimType { get; set; }

    public string Claim { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        if (user.Identity.IsAuthenticated)
        {
            var userClaims = user.Claims.Where(claim => claim.Type.Equals(ClaimType));
            Claims = userClaims.Any() ? userClaims.Select(claim => claim.Value).Aggregate(AddClaims) : "";
        }
    }

    private static string AddClaims(string left, string right) => left + ", " + right;
}

用法:

<ClaimDisplay ClaimType="planet" />

工作demo