Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions src/Middlewares/ApiKeyMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
using DotEnv.Core;
using System.Text;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authorization;
using DotEnv.Core;
using SimpleResults;
using System.Net;

namespace Playtesters.API.Middlewares;

public class ApiKeyMiddleware(RequestDelegate next)
public class ApiKeyMiddleware(
IEnvReader envReader,
RequestDelegate next)
{
private readonly byte[] _apiKeyBytes = Encoding.UTF8.GetBytes(envReader["API_KEY"]);

public async Task InvokeAsync(HttpContext context)
{
var endpoint = context.GetEndpoint();
Expand All @@ -18,22 +23,25 @@ public async Task InvokeAsync(HttpContext context)

if (!context.Request.Headers.TryGetValue("X-Api-Key", out var providedKey))
{
var response = Result.Unauthorized("Missing API Key.");
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsJsonAsync(response);
await Unauthorized(context, "Missing API Key.");
return;
}

var envReader = new EnvReader();
var apiKey = envReader["API_KEY"];
if (!apiKey.Equals(providedKey))
var providedKeyBytes = Encoding.UTF8.GetBytes(providedKey.ToString());

if (!CryptographicOperations.FixedTimeEquals(_apiKeyBytes, providedKeyBytes))
{
var response = Result.Unauthorized("Invalid API Key.");
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsJsonAsync(response);
await Unauthorized(context, "Invalid API Key.");
return;
}

await next(context);
}

private static async Task Unauthorized(HttpContext context, string message)
{
Result result = Result.Unauthorized(message);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsJsonAsync(result);
}
}
1 change: 1 addition & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
builder.Services.AddSwaggerWithApiKey();
builder.Services.AddServices();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddSingleton<IEnvReader>(new EnvReader(envVars));
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite($"Data Source={dataSource}"));

Expand Down
Loading