fix security
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user