pushed api files

pushed middlewares
This commit is contained in:
ElenitaMLG
2024-04-07 02:49:34 +03:00
parent 55eaa0d53a
commit 2ccec617a5
11 changed files with 390 additions and 54 deletions
@@ -0,0 +1,42 @@
namespace API.Middlewares;
public class ApiKeyValidationMiddleware
{
private readonly RequestDelegate _next;
private const string APIKEYNAME = "ApiKey";
public ApiKeyValidationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key was not provided.");
return;
}
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>("ApiKey");
if (string.IsNullOrEmpty(apiKey))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync("Unable to retrieve API key.");
return;
}
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context);
}
}
@@ -0,0 +1,35 @@
using System.Net;
using System.Text;
namespace API.Middlewares;
public class BodyCheckMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context)
{
// Only check the body for POST and PUT requests
if (context.Request.Method == HttpMethods.Post || context.Request.Method == HttpMethods.Put)
{
// Enable buffering so we can read the stream without issues downstream
context.Request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
string requestBody = Encoding.UTF8.GetString(buffer);
context.Request.Body.Seek(0, SeekOrigin.Begin); // Reset the stream for next middleware
// Check if the body is empty
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await context.Response.WriteAsync("Request body cannot be empty.");
return;
}
}
await _next(context);
}
}