41 lines
1.2 KiB
C#
41 lines
1.2 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)
|
||
|
{
|
||
|
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");
|
||
|
}
|
||
|
}
|