ConfigureSwaggerOptions.cs
2,106 bytes
| 1 | using System.Reflection; |
|---|---|
| 2 | using Asp.Versioning.ApiExplorer; |
| 3 | using Microsoft.Extensions.Options; |
| 4 | using Microsoft.OpenApi; |
| 5 | using Swashbuckle.AspNetCore.SwaggerGen; |
| 6 | |
| 7 | namespace WebApp; |
| 8 | |
| 9 | public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions> |
| 10 | { |
| 11 | private readonly IApiVersionDescriptionProvider _descriptionProvider; |
| 12 | |
| 13 | public ConfigureSwaggerOptions(IApiVersionDescriptionProvider descriptionProvider) |
| 14 | { |
| 15 | _descriptionProvider = descriptionProvider; |
| 16 | } |
| 17 | |
| 18 | public void Configure(SwaggerGenOptions options) |
| 19 | { |
| 20 | foreach (var description in _descriptionProvider.ApiVersionDescriptions) |
| 21 | { |
| 22 | options.SwaggerDoc( |
| 23 | description.GroupName, |
| 24 | new OpenApiInfo() |
| 25 | { |
| 26 | Title = $"SplitApp API {description.ApiVersion}", |
| 27 | Version = description.ApiVersion.ToString(), |
| 28 | } |
| 29 | ); |
| 30 | } |
| 31 | |
| 32 | // use fqn for dto descriptions |
| 33 | options.CustomSchemaIds(t => t.FullName); |
| 34 | |
| 35 | options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() |
| 36 | { |
| 37 | Description = |
| 38 | "JWT Authorization header using the Bearer scheme.\r\n<br/>" + |
| 39 | "Enter your token in the text box below.\r\n<br/>" + |
| 40 | "You will get the bearer from the <i>account/login</i> or <i>account/register</i> endpoint.", |
| 41 | Name = "Authorization", |
| 42 | In = ParameterLocation.Header, |
| 43 | Type = SecuritySchemeType.Http, |
| 44 | Scheme = "Bearer", |
| 45 | BearerFormat = "JWT" |
| 46 | }); |
| 47 | |
| 48 | options.DocumentFilter<BearerSecurityRequirementDocumentFilter>(); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public class BearerSecurityRequirementDocumentFilter : IDocumentFilter |
| 53 | { |
| 54 | public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) |
| 55 | { |
| 56 | swaggerDoc.Security = new List<OpenApiSecurityRequirement> |
| 57 | { |
| 58 | new OpenApiSecurityRequirement |
| 59 | { |
| 60 | [new OpenApiSecuritySchemeReference("Bearer", swaggerDoc)] = new List<string>() |
| 61 | } |
| 62 | }; |
| 63 | } |
| 64 | } |
| 65 | |