问题描述
我使用默认的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