ASP.NET Core › API Documentation with Swagger/OpenAPI

How do you document authentication requirements (like a JWT bearer token) in Swagger UI so users can test authenticated endpoints interactively?

Advanced

Answer

Configure AddSecurityDefinition to describe the authentication scheme (e.g., Bearer JWT) and AddSecurityRequirement to apply it globally or per-operation, which adds an 'Authorize' button in Swagger UI where users can paste a token that's then automatically included as an Authorization header on every subsequent 'Try it out' request made from the UI.
builder.Services.AddSwaggerGen(c => {
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
        Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty<string>() }
    });
});
Real-world example A secured internal API lets developers paste a test JWT into Swagger UI's Authorize dialog once, then interactively try every protected endpoint directly from the browser without needing a separate tool like Postman for manual header configuration.

Common follow-ups: How do you apply security requirements to only specific endpoints instead of globally?;How does this differ for API key or OAuth2 authentication schemes?