add AllowAnonymous support for MinimalApi endpoints
All checks were successful
Publish NuGets / build (release) Successful in 37s

Endpoints with [AllowAnonymous] attribute on query/command class
now bypass ASP.NET Core authorization middleware.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
David Nguyen 2026-01-21 12:29:15 -05:00
parent 4bf03446c0
commit 932ee6e632
Signed by: david.nguyen
GPG Key ID: D5FB5A5715829326

View File

@ -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<Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute>();
if (allowAnonymousAttribute != null)
{
builder.AllowAnonymous();
}
return builder;
}
}