Blazor 提供了一组权限控制策略,可以用于限制用户对记录的访问权限。可以借助 AuthenticationStateProvider 获取当前用户信息,以及通过 PolicyBuilder 和 AuthorizeView 组件来实现权限控制。
例如,在 Razor 组件中可以这样使用:
@using Microsoft.AspNetCore.Authorization
You can view the record.
@code {
[CascadingParameter]
private Task authenticationStateTask { get; set; }
protected override async Task OnInitializedAsync()
{
var state = await authenticationStateTask;
var user = state.User;
// 通过判断用户权限来改变 CanViewRecord 策略
// ...
this.StateHasChanged();
}
}
这里定义了一个 CanViewRecord 策略,只有拥有该策略的用户才能查看记录。在 OnInitializedAsync 方法中,可以通过判断用户权限来改变该策略,从而实现不同用户之间的权限控制。