42 lines
1.1 KiB
C#
42 lines
1.1 KiB
C#
namespace API.Middlewares;
|
|
|
|
public class ApiKeyValidationMiddleware
|
|
{
|
|
private const string APIKEYNAME = "ApiKey";
|
|
private readonly RequestDelegate _next;
|
|
|
|
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);
|
|
}
|
|
} |