Added a API Key Attribute but not used yet
This commit is contained in:
parent
d5278a8be9
commit
bc79b507ac
32
Newsbot.Collector.Api/Filters/ApiKeyAuthAttribute.cs
Normal file
32
Newsbot.Collector.Api/Filters/ApiKeyAuthAttribute.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user