ConfigureSwaggerOptions.cs
1,830 bytes
| 1 | using Asp.Versioning.ApiExplorer; |
|---|---|
| 2 | using Microsoft.Extensions.Options; |
| 3 | using Microsoft.OpenApi; |
| 4 | using Swashbuckle.AspNetCore.SwaggerGen; |
| 5 | |
| 6 | namespace SplitApp.UsersService.Hosting; |
| 7 | |
| 8 | public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions> |
| 9 | { |
| 10 | private readonly IApiVersionDescriptionProvider _descriptionProvider; |
| 11 | |
| 12 | public ConfigureSwaggerOptions(IApiVersionDescriptionProvider descriptionProvider) |
| 13 | { |
| 14 | _descriptionProvider = descriptionProvider; |
| 15 | } |
| 16 | |
| 17 | public void Configure(SwaggerGenOptions options) |
| 18 | { |
| 19 | foreach (var description in _descriptionProvider.ApiVersionDescriptions) |
| 20 | { |
| 21 | options.SwaggerDoc( |
| 22 | description.GroupName, |
| 23 | new OpenApiInfo |
| 24 | { |
| 25 | Title = $"SplitApp Users Service {description.ApiVersion}", |
| 26 | Version = description.ApiVersion.ToString(), |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | options.CustomSchemaIds(t => t.FullName); |
| 31 | |
| 32 | options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme |
| 33 | { |
| 34 | Description = "JWT Authorization header using the Bearer scheme.", |
| 35 | Name = "Authorization", |
| 36 | In = ParameterLocation.Header, |
| 37 | Type = SecuritySchemeType.Http, |
| 38 | Scheme = "Bearer", |
| 39 | BearerFormat = "JWT", |
| 40 | }); |
| 41 | |
| 42 | options.DocumentFilter<BearerSecurityRequirementDocumentFilter>(); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public class BearerSecurityRequirementDocumentFilter : IDocumentFilter |
| 47 | { |
| 48 | public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) |
| 49 | { |
| 50 | swaggerDoc.Security = new List<OpenApiSecurityRequirement> |
| 51 | { |
| 52 | new() |
| 53 | { |
| 54 | [new OpenApiSecuritySchemeReference("Bearer", swaggerDoc)] = new List<string>(), |
| 55 | }, |
| 56 | }; |
| 57 | } |
| 58 | } |
| 59 | |