From 877ecef6424ac2766bb3a6315d0f49b243b88f04 Mon Sep 17 00:00:00 2001 From: MrDave1999 Date: Fri, 2 Oct 2026 07:21:14 -0500 Subject: [PATCH] feat(swagger): update dependencies and support anonymous endpoints * Update Microsoft.AspNetCore.OpenApi to 10.0.11 * Update Swashbuckle.AspNetCore to 10.2.3 * Adapt Swagger security configuration to the new OpenAPI API * Hide security requirements for AllowAnonymous endpoints --- src/Extensions/SwaggerExtensions.cs | 47 ++++++++++++++++------------- src/Playtesters.API.csproj | 4 +-- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/src/Extensions/SwaggerExtensions.cs b/src/Extensions/SwaggerExtensions.cs index f7d3ed2..8b0dcd0 100644 --- a/src/Extensions/SwaggerExtensions.cs +++ b/src/Extensions/SwaggerExtensions.cs @@ -1,4 +1,6 @@ -using Microsoft.OpenApi.Models; +using Microsoft.AspNetCore.Authorization; +using Microsoft.OpenApi; +using Swashbuckle.AspNetCore.SwaggerGen; namespace Playtesters.API.Extensions; @@ -6,35 +8,38 @@ public static class SwaggerExtensions { public static IServiceCollection AddSwaggerWithApiKey(this IServiceCollection services) { - services.AddSwaggerGen(c => + services.AddSwaggerGen(options => { - c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme + options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme { - Description = "API Key needed to access the endpoints. X-Api-Key: Your_API_Key", - In = ParameterLocation.Header, Name = "X-Api-Key", Type = SecuritySchemeType.ApiKey, - Scheme = "ApiKeyScheme" + In = ParameterLocation.Header, + Description = "API key required to access protected endpoints." }); - c.AddSecurityRequirement(new OpenApiSecurityRequirement + options.AddSecurityRequirement(document => new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "ApiKey" - }, - Scheme = "ApiKeyScheme", - Name = "X-Api-Key", - In = ParameterLocation.Header - }, - [] - } + [new OpenApiSecuritySchemeReference("ApiKey", document)] = [] }); + + options.OperationFilter(); }); return services; } + + public class ApiKeySecurityOperationFilter : IOperationFilter + { + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + bool isAnonymous = context.ApiDescription.ActionDescriptor.EndpointMetadata + .OfType() + .Any(); + + if (isAnonymous) + { + operation.Security = []; + } + } + } } diff --git a/src/Playtesters.API.csproj b/src/Playtesters.API.csproj index 2ef9c58..1d049c5 100644 --- a/src/Playtesters.API.csproj +++ b/src/Playtesters.API.csproj @@ -7,8 +7,8 @@ - - + +