Newsbot.Collector/Newsbot.Collector.Api/Middleware/ApiKeyAuthentication.cs
James Tombleson a3b1904923
All checks were successful
continuous-integration/drone/pr Build is passing
You can access /health without a api key now.
2023-06-13 21:32:49 -07:00

48 lines
1.4 KiB
C#

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<IConfiguration>();
var keys = appSettings.GetSection("AuthKeys").Get<string[]>();
keys ??= Array.Empty<string>();
//var apiKey = appSettings.GetValue<List<string>>("AuthKeys") ?? "";
foreach (var apiKey in keys)
{
if (apiKey.Equals(extractedApiKey))
{
await _next(context);
return;
}
}
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
}
}