blazor - 为 Blazor WebAssembly 项目创建声明
问题描述
我使用默认的 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" />
工作演示
推荐阅读
- python - Django rest框架序列化程序键错误
- c - 当我尝试在 c 中编译和运行我的程序时,我的权限被拒绝。可能是什么问题呢?
- python - 使用多个条件迭代数据帧的正确方法
- linux - 在 unix 或 shell 中将新行打印为字符串文字
- cmake - 为什么我的
-config.cmake 有 _include_dir 和 _librairies 为空 - javascript - Firestore 特定数据读取不适用于变量,但适用于静态值
- php - 为什么在 PHP 中调用另一个变量时,如果没有呈现变量值?
- unix - 如何在 UNIX 中获取换行符中字符串的最后一个字符
- typescript - 打字稿:根据使用情况推断索引处的元组值
- amazon-web-services - 当 ECS 中的任务被杀死或重启时检测并生成 cloudwatch 警报