namespace WorkFlowCheck.API { public class ApiKeyMiddleware { private readonly RequestDelegate _next; private const string ApiKeyHeaderName = "X-Api-Key"; private readonly ILogger _logger; public ApiKeyMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey)) { _logger.LogWarning("API Key is missing."); context.Response.StatusCode = 401; // Unauthorized context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync("API Key hiányzik."); return; } var appSettings = context.RequestServices.GetRequiredService(); var apiKey = appSettings.GetValue("ApiKey"); if (!apiKey.Equals(extractedApiKey)) { _logger.LogWarning("Invalid API Key."); context.Response.StatusCode = 403; // Forbidden context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync("Helytelen API Key."); return; } await _next(context); } } }