fix security

This commit is contained in:
voltsrage
2026-06-21 19:53:19 +08:00
parent a37fad0e57
commit 7170b6efad
14 changed files with 422 additions and 27 deletions
@@ -1,4 +1,6 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Hl7.Fhir.Serialization;
using Microsoft.Extensions.Options;
using Task = System.Threading.Tasks.Task;
@@ -37,13 +39,15 @@ public class FhirApiKeyOrJwtMiddleware
return;
}
if (string.IsNullOrWhiteSpace(_options.ApiKey))
var configuredKeys = GetConfiguredKeys();
if (configuredKeys.Length == 0)
{
await _next(context);
return;
}
if (context.Request.Headers.TryGetValue("X-Api-Key", out var key) && key == _options.ApiKey)
if (context.Request.Headers.TryGetValue("X-Api-Key", out var suppliedKey)
&& MatchesAnyKey(suppliedKey!, configuredKeys))
{
var claims = new[]
{
@@ -68,4 +72,30 @@ public class FhirApiKeyOrJwtMiddleware
await _next(context);
}
private string[] GetConfiguredKeys()
{
var keys = new List<string>();
if (!string.IsNullOrWhiteSpace(_options.ApiKey))
keys.Add(_options.ApiKey);
foreach (var k in _options.ApiKeys)
{
if (!string.IsNullOrWhiteSpace(k))
keys.Add(k);
}
return keys.ToArray();
}
private static bool MatchesAnyKey(string supplied, string[] configuredKeys)
{
var suppliedBytes = Encoding.UTF8.GetBytes(supplied);
var matched = false;
foreach (var configured in configuredKeys)
{
var configuredBytes = Encoding.UTF8.GetBytes(configured);
if (CryptographicOperations.FixedTimeEquals(suppliedBytes, configuredBytes))
matched = true;
}
return matched;
}
}