91 lines
3.0 KiB
Plaintext
91 lines
3.0 KiB
Plaintext
@inherits ComponentBase
|
|
|
|
<CascadingAuthenticationState>
|
|
<AuthorizeView Context="authContext">
|
|
<Authorized>
|
|
@if (_isAuthorized)
|
|
{
|
|
@ChildContent
|
|
}
|
|
else if (!string.IsNullOrEmpty(NotAuthorizedContent))
|
|
{
|
|
@NotAuthorizedContent
|
|
}
|
|
</Authorized>
|
|
<NotAuthorized>
|
|
@if (!string.IsNullOrEmpty(NotAuthenticatedContent))
|
|
{
|
|
@NotAuthenticatedContent
|
|
}
|
|
</NotAuthorized>
|
|
</AuthorizeView>
|
|
</CascadingAuthenticationState>
|
|
|
|
@code {
|
|
[CascadingParameter] private Task<AuthenticationState>? AuthenticationStateTask { get; set; }
|
|
|
|
[Parameter] public RenderFragment? ChildContent { get; set; }
|
|
[Parameter] public string? NotAuthorizedContent { get; set; }
|
|
[Parameter] public string? NotAuthenticatedContent { get; set; }
|
|
|
|
[Parameter] public string? Permission { get; set; } // 单个权限
|
|
[Parameter] public string[]? AnyPermissions { get; set; } // 多个权限
|
|
[Parameter] public string[]? Roles { get; set; } // 多个角色
|
|
[Parameter] public string? Policy { get; set; } // 策略名称
|
|
|
|
private bool _isAuthorized = false;
|
|
|
|
protected override async Task OnInitializedAsync()
|
|
{
|
|
// 如果 Claims 中没有权限信息,使用 PermissionService 异步检查
|
|
if (AuthenticationStateTask != null)
|
|
{
|
|
var authState = await AuthenticationStateTask;
|
|
var user = authState.User;
|
|
|
|
if (user.Identity?.IsAuthenticated ?? false)
|
|
{
|
|
var userPermissions = user.Claims.Where(c => c.Type == ClaimKeys.Permission).Select(c => c.Value).SingleOrDefault()?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
|
if(userPermissions == null)
|
|
{
|
|
userPermissions = new List<string>();
|
|
}
|
|
// 检查单个权限
|
|
if (Roles?.Length > 0)
|
|
{
|
|
var hasRole = Roles.Any(role => user.IsInRole(role));
|
|
if (!hasRole)
|
|
{
|
|
_isAuthorized = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(Permission))
|
|
{
|
|
var hasAllPermissions = userPermissions.Contains(Permission);
|
|
if (hasAllPermissions)
|
|
{
|
|
_isAuthorized = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (AnyPermissions?.Length > 0)
|
|
{
|
|
var hasAnyPermission = AnyPermissions.Any(p => userPermissions.Contains(p));
|
|
if (!hasAnyPermission)
|
|
{
|
|
_isAuthorized = true;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_isAuthorized = false;
|
|
}
|
|
}
|
|
}
|
|
}
|