abp授权原理
PermissionRequirement
public class PermissionRequirement : AuthorizationHandler<PermissionRequirement>, IAuthorizationRequirement
{
public string PermissionName { get; set; }
public PermissionRequirement(string permissionName)
{
PermissionName = permissionName;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
// 获取用户权限
var userPermissions = PermissionService.GetPermissions(context.User.Identity?.Name);
if (userPermissions != null && userPermissions.Contains(requirement.PermissionName))
{
context.Succeed(requirement);
}
}
}
PermissionAuthorizationPolicyProvider
public class PermissionAuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider, IAuthorizationPolicyProvider
{
public PermissionAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options) : base(options)
{
}
public override async Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
var policy = await base.GetPolicyAsync(policyName);
if (policy != null)
{
return policy;
}
var builder = new AuthorizationPolicyBuilder();
builder.AddRequirements(new PermissionRequirement(policyName));
return builder.Build();
}
}
PermissionService
public class PermissionService
{
public static List<string> GetPermissions(string? name)
{
return new List<string>
{
"auth1",
"auth2",
};
}
}
使用
builder.Services.AddTransient<IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
[Authorize("auth1")]
public IActionResult Privacy()
{
return View();
}