使用授权:
services.AddAuthorization(options =>
{
// 策略结合声明授权
options.AddPolicy("DeleteRolePolicy", policy => policy.RequireClaim("Delete Role"));
options.AddPolicy("AdminRolePolicy", policy => policy.RequireRole("Admin"));
// 策略结合多个角色进行授权
options.AddPolicy("SuperAdminPolicy", policy => policy.RequireRole("Admin", "User"));
options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("Edit Role"));
});
根据是否拥有指定策略决定编辑按钮的显式:
@inject IAuthorizationService AuthorizationService;
<div class="card-footer">
<form method="post" asp-action="DeleteRole" asp-route-id="@role.Id">
@if ((await AuthorizationService.AuthorizeAsync(User, "EditRolePolicy")).Succeeded)
{
<a class="btn btn-primary" style="width: auto" asp-action="EditRole" asp-controller="Admin" asp-route-id="@role.Id">编辑</a>
}
...
同理,后台方法上也要进行限制:
[Authorize(policy:"EditRolePolicy")]
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var role = await _roleManager.FindByIdAsync(id);
...
}