|
| 1 | +using Microsoft.AspNetCore.Authentication; |
| 2 | +using Microsoft.AspNetCore.OpenApi; |
| 3 | +using Microsoft.Extensions.Options; |
| 4 | +using Microsoft.OpenApi.Models; |
| 5 | + |
| 6 | +namespace AspNetCore.SecurityKey.OpenApi; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// A transformer that modifies the OpenAPI document to include security key authentication schemes. |
| 10 | +/// </summary> |
| 11 | +public class SecurityKeyDocumentTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider, IOptions<SecurityKeyOptions> securityKeyOptions) |
| 12 | + : IOpenApiDocumentTransformer |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Transforms the OpenAPI document to include security key authentication schemes. |
| 16 | + /// </summary> |
| 17 | + /// <param name="document">The OpenAPI document to transform.</param> |
| 18 | + /// <param name="context">The context for the OpenAPI document transformation.</param> |
| 19 | + /// <param name="cancellationToken">A token to monitor for cancellation requests.</param> |
| 20 | + /// <returns>A task that represents the asynchronous operation.</returns> |
| 21 | + public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) |
| 22 | + { |
| 23 | + var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync(); |
| 24 | + |
| 25 | + if (!authenticationSchemes.Any(authScheme => string.Equals(authScheme.Name, SecurityKeyAuthenticationDefaults.AuthenticationScheme, StringComparison.InvariantCultureIgnoreCase))) |
| 26 | + return; |
| 27 | + |
| 28 | + var headerName = securityKeyOptions.Value.HeaderName; |
| 29 | + |
| 30 | + var openApiSecurityScheme1 = new OpenApiSecurityScheme |
| 31 | + { |
| 32 | + Type = SecuritySchemeType.ApiKey, |
| 33 | + Scheme = SecurityKeyAuthenticationDefaults.AuthenticationScheme, |
| 34 | + In = ParameterLocation.Header, |
| 35 | + Name = headerName |
| 36 | + }; |
| 37 | + |
| 38 | + var requirements = new Dictionary<string, OpenApiSecurityScheme> |
| 39 | + { |
| 40 | + ["API Key"] = openApiSecurityScheme1 |
| 41 | + }; |
| 42 | + |
| 43 | + document.Components ??= new OpenApiComponents(); |
| 44 | + document.Components.SecuritySchemes = requirements; |
| 45 | + |
| 46 | + foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations)) |
| 47 | + { |
| 48 | + var openApiSecurityScheme = new OpenApiSecurityScheme |
| 49 | + { |
| 50 | + Reference = new OpenApiReference |
| 51 | + { |
| 52 | + Id = "API Key", |
| 53 | + Type = ReferenceType.SecurityScheme |
| 54 | + } |
| 55 | + }; |
| 56 | + var requirement = new OpenApiSecurityRequirement |
| 57 | + { |
| 58 | + [openApiSecurityScheme] = Array.Empty<string>() |
| 59 | + }; |
| 60 | + |
| 61 | + operation.Value.Security.Add(requirement); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments