Added allowlist and denylist, fixed patchy configuration with proper options models, fixed api middleware authorization issues

This commit is contained in:
2025-12-31 03:47:40 +01:00
parent 8d56883e7e
commit aa95308f61
13 changed files with 113 additions and 72 deletions

View File

@@ -1,38 +1,41 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Shared.Models;
namespace Shared;
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
private readonly ApiKeyOptions _configuration;
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
public ApiKeyMiddleware(RequestDelegate next, IOptions<ApiKeyOptions> configuration)
{
_next = next;
_configuration = configuration;
_configuration = configuration.Value;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("X-API-KEY", out StringValues extractedApiKey))
if (!(context.User.Identity?.IsAuthenticated ?? false))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key is missing.");
return;
}
if (!context.Request.Headers.TryGetValue("X-API-KEY", out StringValues extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key is missing.");
return;
}
var validApiKeys = _configuration.GetSection("Embeddingsearch").GetSection("ApiKeys").Get<List<string>>();
#pragma warning disable CS8604
if (validApiKeys == null || !validApiKeys.Contains(extractedApiKey)) // CS8604 extractedApiKey is not null here, but the compiler still thinks that it might be.
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid API Key.");
return;
string[]? validApiKeys = _configuration.ApiKeys;
if (validApiKeys == null || !validApiKeys.ToList().Contains(extractedApiKey))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid API Key.");
return;
}
}
#pragma warning restore CS8604
await _next(context);
}