35 lines
1.1 KiB
C#
35 lines
1.1 KiB
C#
using Application.Endpoints;
|
|
|
|
namespace API.Middlewares;
|
|
|
|
public class ApiKeyMiddleware
|
|
{
|
|
private const string API_KEY_HEADER_NAME = "ApiKey";
|
|
private readonly string _apiKey;
|
|
private readonly RequestDelegate _next;
|
|
|
|
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
|
|
{
|
|
_next = next;
|
|
_apiKey = configuration.GetValue<string>("ApiKeySettings:ApiKey");
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
if (!context.Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out var extractedApiKey))
|
|
{
|
|
context.Response.StatusCode = HttpStatusCodes.Unauthorized; // Unauthorized
|
|
await context.Response.WriteAsync("API Key is missing");
|
|
return;
|
|
}
|
|
|
|
if (!_apiKey.Equals(extractedApiKey))
|
|
{
|
|
context.Response.StatusCode = HttpStatusCodes.Forbidden; // Forbidden
|
|
await context.Response.WriteAsync("Invalid API Key");
|
|
return;
|
|
}
|
|
|
|
await _next(context); // API Key is valid, proceed to the next middleware
|
|
}
|
|
} |