Using API Key Authentication To Secure ASP.NET Core Web API

Introduction

API key authentication will keep the secure line between the API and clients. However, if you wish to have user authentication, go with token-based authentication, aka OAuth2.0. In this article, you will learn how to implement the API Key Authentication to secure the ASP.NET Core Web API by creating a middleware.

API Key Authentication

Step 1. Open Visual Studio Create or open an ASP.NET Core Web API Project. In my case, I’m creating a new project with .NET 6.

Creating a new project

Select a template as shown in the figure below.

Select Template

Configure

Step 2. Run the application, and you will get swagger UI to access WeatherForecast API.

API Key Authentication

Step 3. Create a Middleware Folder, and add a new C# file. I named the new class ApiKeyMiddleware.cs

ApiKeyMiddleware.cs

public class ApiKeyMiddleware {
    private readonly RequestDelegate _next;
    private
    const string APIKEY = "XApiKey";
    public ApiKeyMiddleware(RequestDelegate next) {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context) {
        if (!context.Request.Headers.TryGetValue(APIKEY, out
                var extractedApiKey)) {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Api Key was not provided ");
            return;
        }
        var appSettings = context.RequestServices.GetRequiredService < IConfiguration > ();
        var apiKey = appSettings.GetValue < string > (APIKEY);
        if (!apiKey.Equals(extractedApiKey)) {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized client");
            return;
        }
        await _next(context);
    }
}

The middleware will check the API key in the header and validate the key by extracting it from the header and comparing it with the key defined in the code.

The InvokeAsync method is defined in this middleware so that it will contain the main process. In our case, the main process will be to search and validate the ApiKey header name and value within the httpcontext request headers collection

if (!context.Request.Headers.TryGetValue(APIKEY, out
        var extractedApiKey)) {
    context.Response.StatusCode = 401;
    await context.Response.WriteAsync("Api Key was not provided ");
    return;
}

If there is no header with APIKEY, it will return “Api Key was not provided”

Step 4. Open Program.cs file to register the middleware.

app.UseMiddleware<ApiKeyMiddleware>();

Step 5. Open appsettings.json file and add an API Key.

"XApiKey": "pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp"

Step 6. Run the application, and test the API using POSTMAN without passing the ApiKey in the header. You will get “ApiKey was not provided” message in the payload, as shown in the figure below.

Postman

Passing the wrong API Key

XAPI

Providing the correct API Key

XAPI

Happy Coding!!!

Download the source code in this Github repository.