How to use API keys to secure web APIs in ASP.NET Core

By FoxLearn 12/31/2024 6:47:18 AM   98
API key authentication is a method used to control which applications or services can access your APIs.

Unlike user authentication systems (such as JWT tokens or OAuth 2.0), API keys authenticate the application rather than the individual user.

In ASP.NET Core 7, there are multiple ways to secure your APIs, such as using JWT tokens, ASP.NET Core Identity, or OAuth 2.0. However, API key authentication offers another layer of security by validating the application, not the user.

Implementing API Key Authentication with Middleware

To start, you can implement API key authentication using custom middleware in ASP.NET Core. Middleware allows you to inspect, alter, or route requests as they pass through the pipeline.

First, create a .cs file for your middleware class and include the necessary logic to compare the API key passed in the request header with the value stored in AppSettings.json.

public class CustomApiKeyMiddleware
{
    private readonly IConfiguration _configuration;
    private readonly RequestDelegate _next;
    const string API_KEY = "Api_Key";

    public CustomApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
    {
        _next = next;
        _configuration = configuration;
    }

    public async Task Invoke(HttpContext context)
    {
        bool success = context.Request.Headers.TryGetValue(API_KEY, out var apiKeyFromHeader);
        if (!success)
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("API key is missing.");
            return;
        }

        string expectedApiKey = _configuration[API_KEY];
        if (!expectedApiKey.Equals(apiKeyFromHeader))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Invalid API key.");
            return;
        }

        await _next(context);
    }
}

In your Program.cs file, you can add the middleware to the request pipeline.

app.UseMiddleware<CustomApiKeyMiddleware>();

Use a tool like Postman to test the API by sending requests with the correct or incorrect API key in the request header. When the correct key is passed, access is granted; if the key is incorrect or missing, the server returns an error message.

Implementing API Key Authentication Using Custom Attributes

Alternatively, you can use custom attributes to enforce API key authentication for specific controllers or actions. Here’s how you can implement it using a custom attribute that implements IAsyncActionFilter.

Define a custom attribute that checks for the API key in the request headers.

public class CustomApiKeyAttribute : Attribute, IAsyncActionFilter
{
    private const string API_KEY = "Api_Key";

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        bool success = context.HttpContext.Request.Headers.TryGetValue(API_KEY, out var apiKeyFromHeader);
        if (!success)
        {
            context.Result = new ContentResult()
            {
                StatusCode = 401,
                Content = "API key is missing."
            };
            return;
        }

        IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("AppSettings.json");
        IConfiguration configuration = configurationBuilder.Build();
        string expectedApiKey = configuration[API_KEY];

        if (!expectedApiKey.Equals(apiKeyFromHeader))
        {
            context.Result = new ContentResult()
            {
                StatusCode = 401,
                Content = "Invalid API key."
            };
            return;
        }

        await next();
    }
}

Apply the CustomApiKeyAttribute to a controller or specific actions to require API key validation.

[CustomApiKey]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    // Your API methods
}

API key authentication is a useful approach for controlling access to your Web APIs. It helps identify which applications or services are accessing your API and can track usage patterns, but it does not validate the user making the request.