使用授权:

    1. services.AddAuthorization(options =>
    2. {
    3. // 策略结合声明授权
    4. options.AddPolicy("DeleteRolePolicy", policy => policy.RequireClaim("Delete Role"));
    5. options.AddPolicy("AdminRolePolicy", policy => policy.RequireRole("Admin"));
    6. // 策略结合多个角色进行授权
    7. options.AddPolicy("SuperAdminPolicy", policy => policy.RequireRole("Admin", "User"));
    8. options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("Edit Role"));
    9. });

    根据是否拥有指定策略决定编辑按钮的显式:

    1. @inject IAuthorizationService AuthorizationService;
    2. <div class="card-footer">
    3. <form method="post" asp-action="DeleteRole" asp-route-id="@role.Id">
    4. @if ((await AuthorizationService.AuthorizeAsync(User, "EditRolePolicy")).Succeeded)
    5. {
    6. <a class="btn btn-primary" style="width: auto" asp-action="EditRole" asp-controller="Admin" asp-route-id="@role.Id">编辑</a>
    7. }
    8. ...

    同理,后台方法上也要进行限制:

    1. [Authorize(policy:"EditRolePolicy")]
    2. [HttpGet]
    3. public async Task<IActionResult> EditRole(string id)
    4. {
    5. var role = await _roleManager.FindByIdAsync(id);
    6. ...
    7. }