using Backend.Interface; namespace Backend.Middleware; public sealed class ApiKeyMiddleware { private const string ApiKeyHeader = "X-Api-Key"; private readonly RequestDelegate _next; public ApiKeyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context, IApiKeyStore apiKeyStore) { var path = context.Request.Path.Value ?? ""; if (path.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase)) { await _next(context); return; } if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var extractedKey) || string.IsNullOrWhiteSpace(extractedKey)) { context.Response.StatusCode = 401; await context.Response.WriteAsJsonAsync(new { error = "API key is required." }); return; } if (!await apiKeyStore.ValidateAsync(extractedKey!, context.RequestAborted)) { context.Response.StatusCode = 401; await context.Response.WriteAsJsonAsync(new { error = "Invalid API key." }); return; } await _next(context); } }