This commit is contained in:
andrei-mihnea-cerbu
2024-04-08 01:03:59 +03:00
parent b48d5ee19e
commit 61a55fa735
50 changed files with 80 additions and 52 deletions
@@ -1,42 +1,39 @@
namespace API.Middlewares;
using Application.Endpoints;
public class ApiKeyValidationMiddleware
namespace API.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
public class ApiKeyMiddleware
{
private const string APIKEYNAME = "ApiKey";
private readonly RequestDelegate _next;
private const string API_KEY_HEADER_NAME = "ApiKey";
private readonly string _apiKey;
public ApiKeyValidationMiddleware(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(APIKEYNAME, out var extractedApiKey))
if (!context.Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key was not provided.");
context.Response.StatusCode = HttpStatusCodes.Unauthorized; // Unauthorized
await context.Response.WriteAsync("API Key is missing");
return;
}
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>("ApiKey");
if (string.IsNullOrEmpty(apiKey))
if (!_apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync("Unable to retrieve API key.");
context.Response.StatusCode = HttpStatusCodes.Forbidden; // Forbidden
await context.Response.WriteAsync("Invalid API Key");
return;
}
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context);
await _next(context); // API Key is valid, proceed to the next middleware
}
}