在 Blazor WASM 应用程序中,为对象分配 Identity 用户可以通过以下步骤实现。
services.AddDefaultIdentity
services.AddAuthorization(options => { options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); });
[Authorize(Policy = "RequireAdminRole")] public class MyComponent : ComponentBase { [Inject] private AuthenticationStateProvider AuthenticationStateProvider { get; set; }
private ApplicationUser CurrentUser { get; set; }
protected override async Task OnInitializedAsync()
{
var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authenticationState.User;
// 获取当前用户的 Identity 数据,并将其赋值给对象
var claimsPrincipal = new ClaimsPrincipal(user);
CurrentUser = new ApplicationUser(claimsPrincipal);
}
}
public class ApplicationUser : IdentityUser { public ApplicationUser() { }
public ApplicationUser(ClaimsPrincipal claimsPrincipal)
{
var identity = claimsPrincipal?.Identity as ClaimsIdentity;
if (identity != null)
{
UserName = identity.FindFirst(ClaimTypes.Name)?.Value;
Email = identity.FindFirst(ClaimTypes.Email)?.Value;
}
}
}
这样,就可以通过注入 AuthenticationStateProvider 获取当前用户信息,并将 Identity 数据分配给需要授权的对象。