Skip to content
Closed
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
42 changes: 42 additions & 0 deletions src/OpenApi/src/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,48 @@ The main types provided by this library are:
* `OpenApiOptions`: Options for configuring OpenAPI document generation.
* `IDocumentTransformer`: Transformer that modifies the OpenAPI document generated by the library.

## Customizing Security Schemes

When using `[AllowAnonymous]` on a controller or action, you may want to skip adding security scheme requirements to the OpenAPI document for those endpoints. You can achieve this by implementing a custom `IOpenApiDocumentTransformer` that removes security requirements from endpoints marked with `[AllowAnonymous]`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was my understanding you had to have a transformer to add security requirements -- it is not done automatically by the framework. If that is the case, then the "fix" is not to add another transformer but just to make the original one (not even mentioned here) correctly skip adding a security requirement for an endpoint with AllowAnonymous.

Am I missing something?


### Example

```csharp
public class SkipAnonymousSecurityTransformer : IOpenApiDocumentTransformer
{
public async Task TransformAsync(
OpenApiDocument document,
OpenApiDocumentTransformerContext context,
CancellationToken cancellationToken)
{
var allowAnonymousEndpoints = context.EndpointMetadata
.OfType<Microsoft.AspNetCore.Authorization.IAllowAnonymous>();

if (allowAnonymousEndpoints.Any())
{
foreach (var path in document.Paths.Values)
{
foreach (var operation in path.Operations.Values)
{
operation.Security = null;
}
}
}
}
}
```

Register this transformer in your `Program.cs`:

```csharp
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer<SkipAnonymousSecurityTransformer>();
});
```

For more information on customizing OpenAPI documents, refer to the [official documentation](https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis/openapi).

## Feedback & Contributing

<!-- How to provide feedback on this package and contribute to it -->
Expand Down
Loading