Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion aspnetcore/fundamentals/openapi/customize-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -106,6 +106,52 @@ Operation transformers can also be added to specific endpoint with the <xref:Mic

[!code-csharp[](~/fundamentals/openapi/samples/10.x/WebMinOpenApi/Program.cs?name=snippet_operationtransformer2)]

### Conditionally applying security requirements

In some scenarios, developers may want to apply security requirements to all endpoints except those explicitly marked with the `AllowAnonymous` attribute.

Use an operation transformer, which has access to endpoint metadata through the associated <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription>.

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<AllowAnonymousAttribute>()
.Any();

if (hasAllowAnonymous)
{
return Task.CompletedTask;
}

operation.Security ??= new List<OpenApiSecurityRequirement>();

operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
}] = Array.Empty<string>()
});

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:
Expand Down
Loading