skip to content

In ASP.NET Core 10, how would you use OpenAPI transformers to add a JWT bearer security scheme to a public flight-status API's document?

level: middleimportance: should knowfreq 45%

answer

  1. document, operation and schema transformers
  2. AddDocumentTransformer<T>() with constructor injection
  3. schemas, then operations, then the document
  4. Components.SecuritySchemes plus a requirement
  5. OpenApiSecuritySchemeReference in Microsoft.OpenApi 2

basics

~10 s

Register an IOpenApiDocumentTransformer with options.AddDocumentTransformer<T>() inside AddOpenApi. It adds an http bearer scheme to document.Components.SecuritySchemes; an operation transformer then adds a requirement referencing it to every endpoint that is not anonymous.

solid answer

~40 s

Transformers are hooks the generator runs on the object model before serializing. There are three kinds: **document** transformers (`IOpenApiDocumentTransformer`) see the finished document, **operation** transformers see one path and method with its `ApiDescription`, and **schema** transformers see each type's schema with its `JsonTypeInfo`. You register them in `AddOpenApi(options => ...)` as a type, an instance or a delegate; a type is created from DI for each generation, so its constructor can take `IAuthenticationSchemeProvider`. For the flight-status API, a document transformer checks that the `Bearer` scheme is registered and adds `OpenApiSecurityScheme { Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT" }` to `Components.SecuritySchemes`. A scheme alone requires nothing, so an operation transformer adds an `OpenApiSecurityRequirement` built on `new OpenApiSecuritySchemeReference("Bearer", context.Document)`, skipping endpoints with `IAllowAnonymous` such as the public status lookup.

code

csharp · 20 lines
csharp
internal sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider schemes)
    : IOpenApiDocumentTransformer
{
    public async Task TransformAsync(OpenApiDocument document,
        OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var all = await schemes.GetAllSchemesAsync();
        if (!all.Any(s => s.Name == JwtBearerDefaults.AuthenticationScheme)) return;

        document.Components ??= new OpenApiComponents();
        document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
        document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.Http,
            Scheme = "bearer",
            BearerFormat = "JWT",
            Description = "Access token for delay-alert subscriptions"
        };
    }
}

go deeper

for a junior

Recall that transformers come in three kinds, document, operation and schema, and are registered inside the AddOpenApi options callback.

for a middle

Explain the run order, how type-based transformers get constructor injection, and why a security scheme and a security requirement are two separate pieces.

for a senior

Show a transformer setup that mirrors real authorization: scheme declared only when the handler exists, requirements skipped for anonymous endpoints, nothing hard-coded twice.

for a principal

Decide which contract details belong in shared transformers owned by a platform team and which stay with each API, so published documents stay consistent.

## What a transformer is The built-in generator in `Microsoft.AspNetCore.OpenApi` builds an in-memory `OpenApiDocument` (the Microsoft.OpenApi object model) and only then serializes it. A **transformer** is your code that runs against that object model in between. Everything ApiExplorer cannot know, such as security schemes, contact details, server URLs or extra response codes, is added this way. | Kind | Interface | Sees | Typical use | |---|---|---|---| | Document | `IOpenApiDocumentTransformer` | the whole document plus `DescriptionGroups` | `info`, servers, `components.securitySchemes` | | Operation | `IOpenApiOperationTransformer` | one operation plus its `ApiDescription` | per-endpoint requirements, extra responses | | Schema | `IOpenApiSchemaTransformer` | one schema plus `JsonTypeInfo` | formats, examples, descriptions on a type | ## Registering transformers Each kind can be registered three ways on `OpenApiOptions`: - **By type**: `options.AddDocumentTransformer<BearerSecuritySchemeTransformer>()`. The type is created with `ActivatorUtilities` from the document's service provider each time the document is generated, and disposed afterwards if it implements `IDisposable` or `IAsyncDisposable`. Its constructor can take services; the type itself does not need to be registered. - **By instance**: `options.AddDocumentTransformer(new ContactTransformer())`. - **By delegate**: `options.AddOperationTransformer((operation, context, ct) => ...)`. For a single endpoint, .NET 10 adds `AddOpenApiOperationTransformer(...)` on the endpoint builder; it runs after the global operation transformers for that operation. ## Execution order 1. **Schema transformers** run as each schema is created, in registration order. 2. **Operation transformers** run as each operation is added, in registration order, followed by any endpoint-specific ones. 3. **Document transformers** run last, in registration order, when every operation and schema already exists. With several documents, each document runs its own transformers independently. ## The flight-status scheme The public flight-status API lets anyone read a flight's status, while subscribing to delay alerts needs an access token. Two pieces describe that: - A **security scheme** in `components.securitySchemes`: an `http` scheme with `scheme: bearer` and `bearerFormat: JWT`. The document transformer adds it only when a `Bearer` authentication scheme is really registered, which is why it asks `IAuthenticationSchemeProvider` instead of hard-coding it. - A **security requirement** on the operations that need a token. Declaring the scheme does **not** make anything require it. Requirements go on the document (`document.Security`) for an API that is protected everywhere, or on each operation for a mixed API like this one. The operation transformer skips endpoints whose metadata contains `IAllowAnonymous`, which `.AllowAnonymous()` and `[AllowAnonymous]` add. In Microsoft.OpenApi 2, used by ASP.NET Core 10, a requirement points at the scheme through `new OpenApiSecuritySchemeReference("Bearer", document)`; the older `Reference = new OpenApiReference { ... }` style from Microsoft.OpenApi 1 no longer compiles. Some documentation snippets still show the old style. ## The public info block A second document transformer usually fills what ApiExplorer cannot know about the API as a whole: - `document.Info.Title`, `Description`, `Contact` and `License`. Without it, the title is `"{ApplicationName} | v1"` and the version `1.0.0`. - `document.Servers`. When the document is served by `MapOpenApi`, the server URL is built from the incoming request's scheme, host and path base, so behind a reverse proxy it is only right if forwarded headers are processed. A public API often sets its canonical base URL explicitly instead. ## Things that trip people up - A transformer only changes the **document**. It does not authenticate anything; `[Authorize]` and the JWT handler do that. - The requirement's key must reference the same name you used in `SecuritySchemes`, here `Bearer`. - Because document transformers run last, an operation transformer cannot read a scheme a document transformer is going to add. It only needs the name for the reference, so this does not matter for requirements. - `WithOpenApi()` is not the per-endpoint tool any more; it is obsolete in .NET 10 (`ASPDEPR002`).

  • Why put the requirement in an operation transformer rather than on the document?
    A requirement on `document.Security` applies to every operation, which would mark the anonymous status lookup as needing a token. An operation transformer can read each endpoint's metadata through `context.Description.ActionDescriptor.EndpointMetadata` and skip those carrying `IAllowAnonymous`.
  • Can a type-based transformer depend on a scoped service?
    Yes. A transformer registered with `AddDocumentTransformer<T>()` is created with `ActivatorUtilities` from the service provider used for that document generation, which is the request's scoped provider when served by `MapOpenApi`, and it is disposed afterwards. It is not a singleton you register yourself.
  • How do you change one endpoint's operation without a global transformer?
    Chain `.AddOpenApiOperationTransformer((operation, context, ct) => { ... })` on that endpoint. The delegate is stored as endpoint metadata and runs after the global operation transformers for that operation only.

  • Document transformers run first, so operation transformers can read the schemes they added.
  • A transformer type must be registered with AddSingleton before AddDocumentTransformer<T>() can create it.
  • Adding the scheme to Components.SecuritySchemes makes every operation require the token.
  • In .NET 10 you attach a security requirement per endpoint with WithOpenApi().
  • A security scheme in the document makes ASP.NET Core reject requests without a token.

Assumes ASP.NET Core 10 with Microsoft.OpenApi 2: OpenApiSecuritySchemeReference replaces OpenApiReference, and AddOpenApiOperationTransformer is the per-endpoint hook while WithOpenApi is obsolete.