'How to implement dynamic role based authorization in asp.net ef core framework?

I am implementing a website using .net entity framework 6. It is a web api project. I want to secure my endpoints using dynamic role based authorization.

Example: Let say a user has logged in to the system. Users and roles are stored in database. When he\she trys to do any crud operation, system needs to check whether logged in user has the the permission to do the selected permission by checking user's role.

  • editor - can only access edit endpoint. otherwise system needs to display an error message

can anyone give me a solution for this? If anyone can suggest me any tutorial that would be greatful.



Solution 1:[1]

If you want to use Asp.net core Identity to implement the Role based authorization.

You can refer the following tutorials:

Introduction to Identity on ASP.NET Core

Role-based authorization in ASP.NET Core

Policy-based authorization in ASP.NET Core

ASP.NET Core Identity Roles based Authorization

If you are not using Asp.net core Identity, you can refer the following tutorial, it will use cookies to store user information:

Policy-Based And Role-Based Authorization In ASP.NET Core 3.0 Using Custom Handler

editor - can only access edit endpoint. otherwise system needs to display an error message

Besides, from the above description, it seems that you want to set authorization for each action, if that is the case, you need to add the [Authorize(Roles = "editor")] attribute on the action method, instead of the controller.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zhi Lv