Exciting News - YouTube Channel Launch :
My YouTube Channel is live, featuring the first video on .NET Debugging Techniques in Visual Studio. Check it out and hit subscribe for more tech insights. Let's embark on this learning journey together!
Authorization filters are used to implement authentication and authorization for controller actions.
For example, the Authorize filter is an example of an Authorization filter that we are going to see in action.
API Key Authentication
JWT authentication is commonly employed, but when dealing with third-party APIs, API Key Authentication could be helpful
In this method, a key is included with each request, establishing our legitimacy for making those calls. Typically, this key is transmitted in the headers.
How To Implement it in ASP.NET Core
We can implement it by implementing IAuthorizationFilter
available in Microsoft.AspNetCore.Mvc.Filters
.
It has only one method which we need to implement :
void OnAuthorization(AuthorizationFilterContext context);
In the present scenario, assuming we possess an API key stored in our application settings ( although I will never recommend saving API Key in app setting, use whatever Vault mechanism you prefer to save them)
The task involves verifying this key against each incoming request to determine whether to grant or deny access.
So in our case our implementation would look like this :
The next consideration is how to implement this on our controllers, enabling us to utilize it as an attribute for our controller or action methods.
To achieve this, we must modify our code by inheriting from the Attribute class.
That is all we need to do now we can apply it wherever we want :
Controllers
Action Method
Implementation looks like this :
We can pass API-Key like this in header :
If key does not match then our filter will return un authorized result and it will not allow controller to execute further and on postman it will look like this :
Download the demo code from GitHub Repository
Whenever you’re ready, there are 3 ways I can help you:
Promote yourself to 8800+ subscribers by Sponsoring my Newsletter
Get a FREE eBook from Gumroad that contains 30 .NET Tips (3500+ downloads)
Become a Patron and get access to 200+ .NET Questions and Answers
Special Offers
Pragmatic Clean Architecture: Learn how to confidently ship well-architected production-ready apps using clean architecture. ( New YEAR discounts are on )