在 Blazor WASM 应用程序中,可以使用 ClaimsPrincipal 类和 roles claim 来确定用户的身份和权限。具体方法为:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5000";
options.Audience = "blazorwasmapi";
});
@attribute [Authorize(Roles = "admin")]
Only admins can see this content.
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
private ClaimsPrincipal User;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
User = authState.User;
}
}
从 User 属性中获取的 ClaimsPrincipal 中包含了用户的身份信息(如 NameIdentifier)和角色信息(如 Role)。针对特定的角色,可以使用如下代码判断用户是否属于该角色:
var isAdmin = User.IsInRole("admin");