Added a API Key Attribute but not used yet

This commit is contained in:
James Tombleson 2023-07-14 22:25:11 -07:00
parent d5278a8be9
commit bc79b507ac

View File

@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newsbot.Collector.Domain.Consts;
namespace Newsbot.Collector.Api.Filters;
[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method)]
public class ApiKeyAuthAttribute : Attribute, IAsyncActionFilter
{
private const string ApiKeyHeaderName = "X-API-KEY";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var foundKey))
{
context.Result = new BadRequestResult();
return;
}
var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var apiKeys = config.GetValue<string[]>(ConfigConst.ApiKeys);
foreach (var key in apiKeys ?? Array.Empty<string?>())
{
if (key != foundKey) continue;
await next();
return;
}
context.Result = new BadRequestResult();
}
}