我正在参与 Blazor Web Assembly 的客户端项目。 这是我的程序:
using Blazored.LocalStorage;
using Epicerie_Client;
using Epicerie_Client.Services;
using Epicerie_Client.Services.Interfaces;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddApiAuthorization()
.AddAccountClaimsPrincipalFactory<CustomUserFactory>();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.Configuration.GetValue<string>("BaseAPIUrl")) });
builder.Services.AddScoped<IDepartementService, DepartementService>();
builder.Services.AddScoped<IItemService, ItemService>();
builder.Services.AddScoped<IUniteMesureService, UniteMesureService>();
builder.Services.AddScoped<IGabaritService, GabaritService>();
builder.Services.AddScoped<IEpicerieService, EpicerieService>();
builder.Services.AddScoped<IEpicerieDetailsService, EpicerieDetailsService>();
builder.Services.AddScoped<IGabaritDetailsService, GabaritDetailsService>();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<AuthenticationStateProvider, AuthStateProvider>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
await builder.Build().RunAsync();
这是我的索赔分割器:
public class CustomUserFactory : AccountClaimsPrincipalFactory<RemoteUserAccount>
{
public CustomUserFactory(IAccessTokenProviderAccessor accessor)
: base(accessor)
{
}
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
RemoteUserAccount account,
RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
var claimsIdentity = (ClaimsIdentity)user.Identity;
if (account != null)
{
MapArrayClaimsToMultipleSeparateClaims(account, claimsIdentity);
}
return user;
}
private void MapArrayClaimsToMultipleSeparateClaims(RemoteUserAccount account, ClaimsIdentity claimsIdentity)
{
foreach (var prop in account.AdditionalProperties)
{
var key = prop.Key;
var value = prop.Value;
if (value != null &&
(value is JsonElement element && element.ValueKind == JsonValueKind.Array))
{
claimsIdentity.RemoveClaim(claimsIdentity.FindFirst(prop.Key));
var claims = element.EnumerateArray()
.Select(x => new Claim(prop.Key, x.ToString()));
claimsIdentity.AddClaims(claims);
}
}
}
}
这是我的代币中的角色: “http://schemas.microsoft.com/ws/2008/06/identity/claims/role”:[ “超级实用者”, “管理员”, “实用者” ]
这样,角色声明不会被分割,因此当用户具有多个角色时,这不会按预期工作。
你知道我做错了什么吗?