asp.net core series 49 Identity authorization (on)

1. Overview

Authorization refers to the user’s permission to access resources, such as viewing, editing, adding, deleting, exporting, and downloading of page data. ASP.NET Core authorization provides multiple and flexible methods, including: Razor pages authorization convention, simple authorization, Role authorization, Claim authorization, Policy policy authorization, resource authorization, and view authorization.

1.1 Razor pages agreement authorization

The Razor pages convention is authorized for use with Razor page applications, as well as the Identity Razor Pages library in MVC, and is not applicable to controllers and views in MVC. The following figure applies to the Identity Razor Pages library in MVC:

For Razor pages applications, access permissions can be obtained at startup using authorization conventions (Startup.cs), which authorize users and allow anonymous users to access folders for individual pages. Authorization conventions can be done using cookie authentication or ASP.NET Core Identity. The following is the default authorization configuration of Razor pages after adding a personal account to the MVC project:

 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
              .AddRazorPagesOptions(options =>
              {
                  options. AllowAreas = true;
                  //Authorized users (successful login) are required to access the regional folder (Identity/Account/Manage)
                  options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                  //Authorized users (successful login) are required to access the regional page (Identity/Account/Logout.cshtml)
                  options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
              });

If it is a Razor page application, agree to authorize pages or folders (without areas) under the pages directory, as follows:

 services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        // Pages and folders that require authorized access.
        options.Conventions.AuthorizePage("/Contact");
        options.Conventions.AuthorizeFolder("/Private");
        // Pages and folders that allow anonymous access.
        options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
        options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

The following is combined authorization and anonymous access:

 //Authorized access folders and anonymous files
.AuthorizeFolder("/Private").AllowAnonymousToPage("/Private/Public")
//Folders that allow anonymous access and files that require authorized access
.AllowAnonymousToFolder("/Public").AuthorizePage("/Public/Private")

1.2 Simple Authorization

Simple authorization is a resource that any authenticated user can access. Use filter attributes: Authorization [Authorize] or anonymous [AllowAnonymous], [Authorize] corresponds to the AuthorizeFilter filter, which can be applied to an action or Controller in mvc, and can be applied to a page model class PageModel in razor page, but cannot be applied in the page handler method. Simple authorization in razor page is as follows:

 //Logout page that requires authorized access
    [Authorize]
    public class LogoutModel : PageModel
    {

   // Login page that allows anonymous access
    [AllowAnonymous]
    public class LoginModel : PageModel
    {<!-- -->

Note: Conventional authorization and simple authorization are only for resources that authenticated users can access. That is, resources that can be accessed by users who have successfully logged in.

1.3 Role-based authorization

When a user is created, it may belong to one or more roles. For example: Zhang San may belong to the administrator and user roles, while Li Si only has the user role. Creating and managing these roles depends on the backing store of the authorization process. Role verification is through the IsInRole method on the ClaimsPrincipal class. IsInRole checks that the current user belongs to the role and returns a bool type. It is associated with the role role table and the UserRole user-related role table.

Role-based authorization check is declarative. It is declared on the controller or action to check the permissions of the current user to request resources. The user is associated with a role and checks the permissions of role members.

The following are restrictions on AdministrationController, which can only be accessed by users who are members of the Administrator role:

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

Multiple roles are specified as a comma-separated list:

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

Apply other role authorization attributes at the action level to further restrict access:

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

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

It is also possible to lock the controller (simple authorization) but allow anonymous (unauthenticated) access to individual actions.

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

    [AllowAnonymous]
    public ActionResult Login()
    {
    }
}

For Razor Pages applications, you can use the convention authorization mentioned above, or you can apply AuthorizeAttribute to pageModel, as shown below:

[Authorize(Policy = "RequireAdministratorRole")]
public class UpdateModel : PageModel
{
    public ActionResultOnPost()
    {
    }
}

The following example demonstrates role authorization:

(1) Create AdministrationController and apply Authorize.

 [Authorize(Roles = "Administrator")]
    public class AdministrationController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

(2) After successful login, access to the Administration resource will show rejection, as shown below:

   

(3) Add role role table and UserRole user role table

   

(4) The user logs out, logs in again, accesses the Administration resource, OK

1.4 Claim-based authorization

When a user is created, it may be assigned one or more Claims. Claims statement indicates which user name value pairs. Claims-based authorization checks the value of the Claims statement and allows access to resources based on that value. Associated with the UserClaim user claim form

(1) Add Claims policy

First, in the Startup.cs file, you need to register the policy policy. In the example below, the policy name is EmployeeOnly, the policy type ClaimType is EmployeeNumber, and the policy type value can also be included.

 services.AddAuthorization(options =>
    {
        options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("EmployeeNumber"));
        //Or a strategy with claimType type and requiredValues value
        //options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", " "5"));
    });

(2) Apply the policy name to the controller

 [Authorize(Policy = "EmployeeOnly")]
    public class EmployeeController : Controller
    {
        // GET: /<controller>/
        ?public IActionResult Index()
       {
           Return View();
        }
   }

(3) The user logs in, accesses the Employee resource, and access is denied

(4) Insert a piece of data in the UserClaim claim table (register the EmployeeOnly claim strategy above, and only require verification of the claimType type. Therefore, the value of 1 in the claimvalue in the table does not work. If you want to use the claimvalue in the table, you can enter the requiredValues value when registering EmployeeOnly )

(5) The user logs out, logs in again, and accesses Employee resources, OK

references

Authorization