ASP.NET Core 2.2 & 3 REST API #24 — Setting up ApiKey-Based Authentication

Theodoros Ntakouris
3 min readAug 29, 2019

--

Up Next: Response caching using Redis

Up until now, we are using JWTs to authenticate our APIs. In this tutorial, we are going to demonstrate how to use a static key throughout your API, or one per type-thing we serve.

An example would be consuming Github’s API. It provides a developer key which you send back with every request so that Github knows it is you. That key does not change.

There are many ways to do that. Header, Requests Body, Request Parameters and different ways to handle that on the framework side. We are going to use an api key header to extract the key from.

There are tons of tutorials online using claims and policies but we are going to do that, but this is all about simplicity and effectiveness.

We’re going to use a Filter to do that. Let’s create one under Filters and call this ApiKeyAuthAttribute : Attribute, IAsyncActionFilter .

We’re going to use the just created [ApiKeyAuthAttribute] to decorate any endpoint we need to have such auth. The call is going to automatically go through the OnActionExecutionAsync method that we are forced to implement due to the filter interface. Remember, a filter is a middleware actually.

We’ve already seen how filters work on the validation part, so we’re just going to add some logic to check the api key.

Just add some "ApiKey": "MySecretKey" on our appsettings.json .

We can easily then just access the request, thus the headers inside our filter and just compare this with our app settings one.

  • First check if the Api Key header exists
  • Then, read and compare the key with our secret one

We can’t have the key read once at the constructor level because we would then be required to instantiate this service when we are using this as an attribute but we are able to get an instance of the configuration service through the HttpContext . This makes testability a bit harder but we just need to mock the configuration. Unit testing this along with other parts of the app are going to be demonstrated in a later instructional video.

That’s all you need to do. You can also change this to use request parameters by extracting the potential value a different way.

We don’t need to register anything, we can just use this attribute on a controller-level or on a method/endpoint level by the [AttributeUsage] attribute.

You are supposed to use this on a controller that another service uses, not that an actual user consumes. Here’s some screenshot examples:

It’s simple as that to have api key based auth. You can connect this to other systems/databases easily to track and restrict usage if you’d like.

Up Next: Response caching using Redis

Code is available on Github and the instructional videos are located on YouTube.

Keep Coding

--

--

Responses (1)