diff --git a/aspnetcore/fundamentals/openapi/customize-openapi.md b/aspnetcore/fundamentals/openapi/customize-openapi.md index 358970313384..aa6cc69bb9ef 100644 --- a/aspnetcore/fundamentals/openapi/customize-openapi.md +++ b/aspnetcore/fundamentals/openapi/customize-openapi.md @@ -5,7 +5,7 @@ description: Learn how to customize OpenAPI documents in an ASP.NET Core app ms.author: wpickett monikerRange: '>= aspnetcore-9.0' ms.custom: mvc -ms.date: 10/29/2025 +ms.date: 03/20/2026 uid: fundamentals/openapi/customize-openapi --- # Customize OpenAPI documents @@ -106,6 +106,52 @@ Operation transformers can also be added to specific endpoint with the . + +The following example demonstrates how to skip adding a security requirement for endpoints that have the `AllowAnonymousAttribute` applied: + +```csharp +internal sealed class AuthOperationTransformer : IOpenApiOperationTransformer +{ + public Task TransformAsync( + OpenApiOperation operation, + OpenApiOperationTransformerContext context, + CancellationToken cancellationToken) + { + var hasAllowAnonymous = context.Description.ActionDescriptor.EndpointMetadata + .OfType() + .Any(); + + if (hasAllowAnonymous) + { + return Task.CompletedTask; + } + + operation.Security ??= new List(); + + operation.Security.Add(new OpenApiSecurityRequirement + { + [new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Id = "Bearer", + Type = ReferenceType.SecurityScheme + } + }] = Array.Empty() + }); + + return Task.CompletedTask; + } +} +``` + +Use this approach instead of document transformers when conditional logic based on endpoint metadata is required. This transformer adds security *requirements* per operation and assumes the security *scheme* is already registered at the document level. For an example of registering the Bearer security scheme, see the `BearerSecuritySchemeTransformer` in the [Use document transformers](#use-document-transformers) section. + ## Use schema transformers Schemas are the data models that are used in request and response bodies in an OpenAPI document. Schema transformers are useful when a modification: