2023-06-12 15:15:04 -07:00
|
|
|
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)
|
|
|
|
{
|
2023-06-13 21:32:49 -07:00
|
|
|
// allow access to /health without auth
|
|
|
|
if (context.Request.Path == "/health")
|
|
|
|
{
|
|
|
|
await _next(context);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-06-12 15:15:04 -07:00
|
|
|
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");
|
|
|
|
}
|
|
|
|
}
|