Skip to main content

Exercise 3: API Key Authentication

Objective

Implement API key authentication middleware

Implementation

public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string API_KEY_HEADER = "X-API-Key";

public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(API_KEY_HEADER, out var providedKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsJsonAsync(new { error = "API Key missing" });
return;
}

// Validate API key from database

await _next(context);
}
}

Expected Outcome

  • API key validation
  • Per-key rate limiting
  • Key management system

Challenge

  • Store keys in database
  • Add key expiration
  • Track API key usage