Problem
I was looking for a solution to provide a minimal solution for API Keys with minimal effort.
Solution
ApiKeyMiddleware:
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string APIKEYNAME = "ApiKey";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Api key was not provided.");
return;
}
}
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValaue<string>(APIKEYNAME);
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context)
}
Then just register the Project.cs:
app.UseMiddleware<ApiKeyMiddleware>();
Comments