Create a Custom Authorization Policy in ASP.NET Core in 3 Steps

Sriram Kumar Mannava
3 min readJun 26, 2023

Authorization is the process of validating and deciding if a user is allowed to do something that is being requested.

In ASP.NET Core there are different approaches to implement Authorization for user requests in a Web API.

They are —

  1. Role based Authorization
  2. Claims based Authorization
  3. Policy based Authorization

I have explained all of these in detail with examples in my blog post here — https://codingramen.com/blog/how-to-authorize-requests-in-asp-net-core-web-api/

Role based and Claims based Authorization are straight-forward and can be used when we need to validate user access based on the presence of a specific Role or a Claim present in the User Identity created post Authentication.

We go for a Policy based Authorization when we are required to combine two or more authorization requirements for validation, or need to apply some business logic.

We can create a Custom Policy and use it for Authorization in 3 steps -

I. Create a Requirement — In any approach of Authorization, be it Role based or Claims based; .NET creates a Policy behind the scenes and applies it for Authorization. We create our own Requirement, which is like a Template for it to be ticked true.

II. Create a Handler — An Authorization Handler takes in a Requirement and validates it against the request. It decides and marks if the Requirement is fulfilled or not. ASP.NET Core has a default Authorization Handler, which we override and add our custom logic.

III. Add the Requirement to a Policy — After we create our Custom Requirement and Handler, we create and add these to a Custom Policy. Our Authorization now works based on this new Policy that is passed over in the Authorize attribute as a parameter. Also the Handler implementation is registered as a Service so that it is used in all places where IAuthorizationHandler is called.

Read the full Article on Authorization — https://codingramen.com/blog/how-to-authorize-requests-in-asp-net-core-web-api/

Subscribe to my Newsletter and get notified — https://codingramen.substack.com/

--

--

Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger