.netasp.net-coreasp.net-roles

Policy-based authorization vs authorize with role in .Net Core


What is the difference between using policy-based authorization and authorize with role, or there is no difference?

[Authorize(Policy = "RequiredAdminRole")]

and

[Authorize(Roles = "Admin")]

Solution

  • Policy-based authorization gives you more flexibility. You can use custom authorization handlers with policies to add more complex logic than just checking if your user has a specific role. For example, you have some roles mappings in your database. You can create a policy that will check if your user is authorized according to that data or that can be any custom logic. You can also create policy only with .RequireRole("Admin") which technically will do the same as an attribute [Authorize(Roles = "Admin")] Take a look at how to implement custom authorization handlers in documentation