namespace Newsbot.Collector.Api.Authentication; public class ApiKeyAuthAuthentication { public const string HeaderApiKey = "x-api-key"; private readonly RequestDelegate _next; public ApiKeyAuthAuthentication(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // allow access to /health without auth if (context.Request.Path == "/health") { await _next(context); return; } if (!context.Request.Headers.TryGetValue(HeaderApiKey, out var extractedApiKey)) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Api key was not provided."); return; } var appSettings = context.RequestServices.GetRequiredService(); var keys = appSettings.GetSection("AuthKeys").Get(); keys ??= Array.Empty(); //var apiKey = appSettings.GetValue>("AuthKeys") ?? ""; foreach (var apiKey in keys) { if (apiKey.Equals(extractedApiKey)) { await _next(context); return; } } context.Response.StatusCode = 401; await context.Response.WriteAsync("Unauthorized"); } }