ASP.NET Core 中基于角色的授权Role-based authorization in ASP.NET Core

创建一个标识时它可能属于一个或多个角色。When an identity is created it may belong to one or more roles. 例如,爱妻 Tracy 可能属于管理员和用户角色,同时 Scott 可能仅属于用户角色。For example, Tracy may belong to the Administrator and User roles whilst Scott may only belong to the User role. 如何创建和管理这些角色取决于后备存储的授权过程。How these roles are created and managed depends on the backing store of the authorization process. 角色公开为通过开发人员IsInRole方法ClaimsPrincipal类。Roles are exposed to the developer through the IsInRole method on the ClaimsPrincipal class.

添加角色检查Adding role checks

基于角色的授权检查是声明性—开发人员将其嵌入在其代码中,对控制器或在控制器内的动作指定当前用户必须是成员的访问请求的资源的角色。Role-based authorization checks are declarative—the developer embeds them within their code, against a controller or an action within a controller, specifying roles which the current user must be a member of to access the requested resource.

例如,下面的代码上限制任何操作的访问权限AdministrationController谁是其成员的用户到Administrator角色:For example, the following code limits access to any actions on the AdministrationController to users who are a member of the Administrator role:

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}

以逗号分隔的列表,可以指定多个角色:You can specify multiple roles as a comma separated list:

[Authorize(Roles = "HRManager,Finance")]
public class SalaryController : Controller
{
}

将仅可由成员的用户访问此控制器的HRManager角色或Finance角色。This controller would be only accessible by users who are members of the HRManager role or the Finance role.

如果在应用多个属性,则访问用户必须是指定; 的所有角色的成员下面的示例要求用户必须是两个成员PowerUserControlPanelUser角色。If you apply multiple attributes then an accessing user must be a member of all the roles specified; the following sample requires that a user must be a member of both the PowerUser and ControlPanelUser role.

[Authorize(Roles = "PowerUser")]
[Authorize(Roles = "ControlPanelUser")]
public class ControlPanelController : Controller
{
}

通过应用其他角色授权属性在操作级别,可以进一步限制访问权限:You can further limit access by applying additional role authorization attributes at the action level:

[Authorize(Roles = "Administrator, PowerUser")]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }

    [Authorize(Roles = "Administrator")]
    public ActionResult ShutDown()
    {
    }
}

中的上一代码片段成员Administrator角色或PowerUser角色可访问该控制器并SetTime操作,但只有的成员Administrator角色可以访问ShutDown操作。In the previous code snippet members of the Administrator role or the PowerUser role can access the controller and the SetTime action, but only members of the Administrator role can access the ShutDown action.

您还可以锁定一个控制器,但允许匿名、 未经身份验证访问各项操作。You can also lock down a controller but allow anonymous, unauthenticated access to individual actions.

[Authorize]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }

    [AllowAnonymous]
    public ActionResult Login()
    {
    }
}

为 Razor 页面AuthorizeAttribute可以通过以下任一方式应用:For Razor Pages, the AuthorizeAttribute can be applied by either:

  • 使用约定,或Using a convention, or
  • 将应用AuthorizeAttributePageModel实例:Applying the AuthorizeAttribute to the PageModel instance:
[Authorize(Policy = "RequireAdministratorRole")]
public class UpdateModel : PageModel
{
    public ActionResult OnPost()
    {
    }
}

重要

筛选器属性,包括AuthorizeAttribute、 仅应用于 PageModel 和不能应用于特定页面处理程序方法。Filter attributes, including AuthorizeAttribute, can only be applied to PageModel and cannot be applied to specific page handler methods.

基于策略角色检查Policy based role checks

此外可以使用新的策略语法,其中一名开发人员将策略在启动时注册为授权服务配置的一部分表示角色的要求。Role requirements can also be expressed using the new Policy syntax, where a developer registers a policy at startup as part of the Authorization service configuration. 这通常发生在ConfigureServices()在您Startup.cs文件。This normally occurs in ConfigureServices() in your Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdministratorRole",
             policy => policy.RequireRole("Administrator"));
    });
}

使用应用策略Policy属性上的AuthorizeAttribute属性:Policies are applied using the Policy property on the AuthorizeAttribute attribute:

[Authorize(Policy = "RequireAdministratorRole")]
public IActionResult Shutdown()
{
    return View();
}

如果你想要指定多个允许的角色中一项要求,则您可以将他们指定为参数RequireRole方法:If you want to specify multiple allowed roles in a requirement then you can specify them as parameters to the RequireRole method:

options.AddPolicy("ElevatedRights", policy =>
                  policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));

此示例中授权用户属于AdministratorPowerUserBackupAdministrator角色。This example authorizes users who belong to the Administrator, PowerUser or BackupAdministrator roles.

将角色服务添加到标识Add Role services to Identity

追加AddRoles添加角色服务:Append AddRoles to add Role services:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}