using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; namespace SecuringWebApiUsingApiKey.Middleware { public class ApiKeyMiddleware { private readonly RequestDelegate _next; private const string APIKEYNAME = "ApiKey"; public ApiKeyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var appSettings = context.RequestServices.GetRequiredService(); string apiCheck = appSettings.GetValue("ApiCheck"); if (apiCheck == "e913aab4-c2c5-4e33-ad24-d25848f748e7") { await _next(context); return; } if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey)) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Api Key was not provided. (Using ApiKeyMiddleware) "); return; } var apiKey = appSettings.GetValue(APIKEYNAME); string[] keys = apiKey.Split(","); bool tokenok = false; for (int i = 0; i < keys.Length; i++) if (keys[i] == extractedApiKey) { tokenok = true; break; } //if (!apiKey.Equals(extractedApiKey)) if (!tokenok) { context.Response.StatusCode = 401; await context.Response.WriteAsync ("Unauthorized client. (Using ApiKeyMiddleware)"); return; } await _next(context); } } }