Added cache key format for api key validation

This commit is contained in:
2026-02-12 09:59:47 +01:00
parent 5efe591f85
commit 7b38662f8f

View File

@@ -16,6 +16,8 @@ public class ApiKeySchemeHandler : AuthenticationHandler<ApiKeySchemeOptions>
private readonly DatabaseRepository<ApiKey> ApiKeyRepository; private readonly DatabaseRepository<ApiKey> ApiKeyRepository;
private readonly IMemoryCache MemoryCache; private readonly IMemoryCache MemoryCache;
private const string CacheKeyFormat = $"Moonlight.Api.{nameof(ApiKeySchemeHandler)}.{{0}}";
public ApiKeySchemeHandler( public ApiKeySchemeHandler(
IOptionsMonitor<ApiKeySchemeOptions> options, IOptionsMonitor<ApiKeySchemeOptions> options,
ILoggerFactory logger, ILoggerFactory logger,
@@ -38,7 +40,9 @@ public class ApiKeySchemeHandler : AuthenticationHandler<ApiKeySchemeOptions>
if (authHeaderValue.Length > 32) if (authHeaderValue.Length > 32)
return AuthenticateResult.Fail("Invalid api key specified"); return AuthenticateResult.Fail("Invalid api key specified");
if (!MemoryCache.TryGetValue<ApiKeySession>(authHeaderValue, out var apiKey)) var cacheKey = string.Format(CacheKeyFormat, authHeaderValue);
if (!MemoryCache.TryGetValue<ApiKeySession>(cacheKey, out var apiKey))
{ {
apiKey = await ApiKeyRepository apiKey = await ApiKeyRepository
.Query() .Query()
@@ -49,7 +53,7 @@ public class ApiKeySchemeHandler : AuthenticationHandler<ApiKeySchemeOptions>
if (apiKey == null) if (apiKey == null)
return AuthenticateResult.Fail("Invalid api key specified"); return AuthenticateResult.Fail("Invalid api key specified");
MemoryCache.Set(authHeaderValue, apiKey, Options.LookupCacheTime); MemoryCache.Set(cacheKey, apiKey, Options.LookupCacheTime);
} }
else else
{ {