From 932ee6e6327faca1a7fd914a69acd105e9331343 Mon Sep 17 00:00:00 2001 From: David Nguyen Date: Wed, 21 Jan 2026 12:29:15 -0500 Subject: [PATCH] add AllowAnonymous support for MinimalApi endpoints Endpoints with [AllowAnonymous] attribute on query/command class now bypass ASP.NET Core authorization middleware. Co-Authored-By: Claude Opus 4.5 --- .../EndpointRouteBuilderExtensions.cs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Svrnty.CQRS.MinimalApi/EndpointRouteBuilderExtensions.cs b/Svrnty.CQRS.MinimalApi/EndpointRouteBuilderExtensions.cs index fe5e3f0..1a6498d 100644 --- a/Svrnty.CQRS.MinimalApi/EndpointRouteBuilderExtensions.cs +++ b/Svrnty.CQRS.MinimalApi/EndpointRouteBuilderExtensions.cs @@ -83,7 +83,8 @@ public static class EndpointRouteBuilderExtensions .Produces(200, queryMeta.QueryResultType) .Produces(400) .Produces(401) - .Produces(403); + .Produces(403) + .WithAllowAnonymousIfAttributePresent(queryMeta.QueryType); } private static void MapQueryGet( @@ -146,7 +147,8 @@ public static class EndpointRouteBuilderExtensions .Produces(200, queryMeta.QueryResultType) .Produces(400) .Produces(401) - .Produces(403); + .Produces(403) + .WithAllowAnonymousIfAttributePresent(queryMeta.QueryType); } public static IEndpointRouteBuilder MapSvrntyCommands(this IEndpointRouteBuilder endpoints, string routePrefix = "api/command") @@ -213,7 +215,8 @@ public static class EndpointRouteBuilderExtensions .Produces(200) .Produces(400) .Produces(401) - .Produces(403); + .Produces(403) + .WithAllowAnonymousIfAttributePresent(commandMeta.CommandType); } private static void MapCommandWithResult( @@ -260,6 +263,17 @@ public static class EndpointRouteBuilderExtensions .Produces(200, commandMeta.CommandResultType) .Produces(400) .Produces(401) - .Produces(403); + .Produces(403) + .WithAllowAnonymousIfAttributePresent(commandMeta.CommandType); + } + + private static RouteHandlerBuilder WithAllowAnonymousIfAttributePresent(this RouteHandlerBuilder builder, Type type) + { + var allowAnonymousAttribute = type.GetCustomAttribute(); + if (allowAnonymousAttribute != null) + { + builder.AllowAnonymous(); + } + return builder; } }