diff --git a/WorkFlow.API/Extensions/DIExtensions.cs b/WorkFlow.API/Extensions/DIExtensions.cs index 61dadda..565590d 100644 --- a/WorkFlow.API/Extensions/DIExtensions.cs +++ b/WorkFlow.API/Extensions/DIExtensions.cs @@ -5,7 +5,7 @@ namespace WorkFlow.API.Extensions { public static class DIExtensions { - public static IServiceCollection AddAPIKeyAuth(this IServiceCollection services, Func isValidKey, string headerName = "X-API-Key") + public static IServiceCollection AddAPIKeyAuth(this IServiceCollection services, Func isValidKey, string headerName = "X-API-Key") => services.AddSingleton(provider => new(isValidKey: isValidKey, headerName: headerName)); public static IServiceCollection AddAPIKeyAuth(this IServiceCollection services, APIKeyAuthOptions options) diff --git a/WorkFlow.API/Filters/ApiKeyAuthFilter.cs b/WorkFlow.API/Filters/ApiKeyAuthFilter.cs index e9525fe..b69a6c2 100644 --- a/WorkFlow.API/Filters/ApiKeyAuthFilter.cs +++ b/WorkFlow.API/Filters/ApiKeyAuthFilter.cs @@ -3,16 +3,12 @@ using Microsoft.AspNetCore.Mvc; namespace WorkFlow.API.Filters { - public class APIKeyAuthFilter(Func isValidKey, string headerName = "X-API-Key") : IAuthorizationFilter + public class APIKeyAuthFilter(Func isValidKey, string headerName = "X-API-Key") : IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { - string? apiKey = context.HttpContext.Request.Headers[headerName]; - - if (apiKey is null || !isValidKey(apiKey)) - { + if (!isValidKey(context.HttpContext.Request.Headers[headerName])) context.Result = new UnauthorizedResult(); - } } } } \ No newline at end of file diff --git a/WorkFlow.API/Models/APIKeyAuthOptions.cs b/WorkFlow.API/Models/APIKeyAuthOptions.cs index 876c1f2..a76c127 100644 --- a/WorkFlow.API/Models/APIKeyAuthOptions.cs +++ b/WorkFlow.API/Models/APIKeyAuthOptions.cs @@ -2,7 +2,7 @@ { public class APIKeyAuthOptions { - public required string Key { get; init; } + public string? Key { get; init; } = null; public string HeaderName { get; init; } = "X-API-Key"; diff --git a/WorkFlow.API/Program.cs b/WorkFlow.API/Program.cs index 3655c3e..5ea2b3e 100644 --- a/WorkFlow.API/Program.cs +++ b/WorkFlow.API/Program.cs @@ -39,11 +39,11 @@ try }); bool disableAPIKeyAuth = config.GetValue("DisableAPIKeyAuth") && builder.IsDevOrDiP(); - if (!disableAPIKeyAuth) + if (disableAPIKeyAuth) + builder.Services.AddAPIKeyAuth(new()); + else if (config.GetSection("APIKeyAuth").Get() is APIKeyAuthOptions options) - { - builder.Services.AddAPIKeyAuth(options); - } + builder.Services.AddAPIKeyAuth(options); else throw new("The API Key Authorization configuration is not available in the app settings, even though the app is not in development or DiP mode and API Key Authorization is not disabled.");