Using API Key Authorization with Middleware and Attribute on ASP.NET Core Web API

Murat Süzen
2 min readApr 22, 2022

--

Hello, in this article, we will API Key authorization on ASP.NET Core Web API with middleware and attribute. We will create an ASP.NET Core Web API project named ApiKeyAuthentication.

Using Middleware

We add a Middlewares folder to the project and add a class called ApiKeyMiddleware.

ApiKeyMiddleware.cs

When we examine the code, we check the X-API-KEY in HttpContext Headers. If there is a value, we compare it with the X-API-KEY value in appsettings. If the value is true, we continue the process.

Program.cs

Here we should pay attention to the swagger configuration. If we want to send api key with Swagger, we configure AddSecurityDefinition and AddSecurityRequirement in the AddSwaggerGen method.

appsettings.json

Using Atrribute

We create a folder named Attributes and create a class called ApiKey Attribute.

ApiKeyAttribute.cs

As we did in the Middleware class, we continue the process after reaching the api key value in the HttpContext Header and verifying it. [AttributeUsage] is the part we should pay attention to here. With this attribute, we set in which parts of the class our class can be used.

WeatherForecastController.cs
401 Error
Authorize
Success

You can download the project here. Please let me know if there are typos in my post.

--

--

Murat Süzen
Murat Süzen

Written by Murat Süzen

Married, one child, blogger (muratsuzen.github.io) is a software developer.

Responses (1)