API Key Authentication in ASP .NET Core

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 :

API Key Authentication in ASP .NET Core

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. API Key Authentication in ASP .NET Core

That is all we need to do now we can apply it wherever we want :

  • Controllers

  • Action Method

Implementation looks like this : API Key Authentication in ASP .NET Core

We can pass API-Key like this in header : API Key Authentication in ASP .NET Core

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 : API Key Authentication in ASP .NET Core

Download the demo code from GitHub Repo

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place