Role-based Authorization in ASP.Net Core (With Custom Authentication Handler)

Опубликовано: 26 Октябрь 2024
на канале: DotNet Core Central
21,013
190

In this video, I am going to take a deep-dive into ASP.Net Core role-based Authorization. Authorization is the process to find out what action a user can perform. In the case of a REST API, it can be the resources a user can access. Or a particular HTTP verb associated with a resource.

For example, let us say we have an e-commerce inventory management application. In the application, the warehouse manager manages the record of the entire inventory of the warehouse. And let us say that there is a REST API for Inventory. Also, the API exposes GET to return all items in the inventory. Plus a POST to add items to the inventory. In this case, the warehouse manager with administrative privilege will be able to access both the GET and POST methods of the Inventory resource. Whereas a warehouse employee will be able to access only the GET method of the Inventory resource.

For authorization to work, the user has to be authenticated first. This is something I discussed in my previous two videos on authentication. To find out what a user can access we need the user's identity. And the identity of an user is set only after the user is authenticated.

To understand the code examples here and how it ties with authentication I strongly suggest to view my previous two videos on Authentication.

   • ASP.NET Core Authentication with Cust...  
   • ASP.NET Core Authentication with JWT ...  

In role-based authorization, checks are done with an attribute-based declaration. We will use AuthorizeAttribute attribute in the method which we want to allow access to a specific role. And the role is identified from the Identity of a user.