diff --git a/EasyFortniteStats-ImageApi.csproj b/EasyFortniteStats-ImageApi.csproj index 7097937..a019066 100644 --- a/EasyFortniteStats-ImageApi.csproj +++ b/EasyFortniteStats-ImageApi.csproj @@ -10,10 +10,10 @@ - - - - + + + + diff --git a/Middleware/ApiKeyAuthenticationMiddleware.cs b/Middleware/ApiKeyAuthenticationMiddleware.cs new file mode 100644 index 0000000..5b55ea7 --- /dev/null +++ b/Middleware/ApiKeyAuthenticationMiddleware.cs @@ -0,0 +1,34 @@ +namespace EasyFortniteStats_ImageApi.Middleware; + +public class ApiKeyAuthenticationMiddleware(RequestDelegate next, IConfiguration configuration) +{ + private readonly string? _apiKey = configuration["API_KEY"] ?? Environment.GetEnvironmentVariable("API_KEY"); + + public async Task InvokeAsync(HttpContext context) + { + // If no API key is configured, skip authentication + if (string.IsNullOrEmpty(_apiKey)) + { + await next(context); + return; + } + + // Check if Authorization header is present + if (!context.Request.Headers.TryGetValue("Authorization", out var extractedApiKey)) + { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("API Key is missing"); + return; + } + + // Validate the API key + if (!_apiKey.Equals(extractedApiKey)) + { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("Unauthorized client"); + return; + } + + await next(context); + } +} diff --git a/Program.cs b/Program.cs index bba0778..2395262 100644 --- a/Program.cs +++ b/Program.cs @@ -1,5 +1,6 @@ using AsyncKeyedLock; using EasyFortniteStats_ImageApi; +using EasyFortniteStats_ImageApi.Middleware; var builder = WebApplication.CreateBuilder(args); @@ -18,6 +19,9 @@ var app = builder.Build(); +// Add API Key authentication middleware +app.UseMiddleware(); + if (app.Environment.IsDevelopment()) { app.UseSwagger(); diff --git a/README.md b/README.md index e78426a..df73088 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ # EasyFortniteStats ImageAPI + This is the internal API written in C# to generate the images for the [EasyFortniteStats Discord Bot](https://easyfnstats.com). ## Usage -This api isn't intended to be used in any other Discord related projects. Also commercial use is not allowed. This project can be used in following cases: + +This api isn't intended to be used in any other Discord related projects. Also commercial use is not allowed. This project can be used in following cases: + - Private non-commercial use - Public non-commercial projects (with credit) - Educational use -- Open source projects (with credit) \ No newline at end of file +- Open source projects (with credit)