diff --git a/Todo.Api/Extensions/OpenApiOptionsExtensions.cs b/Todo.Api/Extensions/OpenApiOptionsExtensions.cs new file mode 100644 index 0000000..8bd1cc1 --- /dev/null +++ b/Todo.Api/Extensions/OpenApiOptionsExtensions.cs @@ -0,0 +1,37 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi.Models; + +public static class OpenApiOptionsExtensions +{ + public static OpenApiOptions AddBearerTokenAuthentication(this OpenApiOptions options) + { + var scheme = new OpenApiSecurityScheme() + { + Type = SecuritySchemeType.Http, + Name = IdentityConstants.BearerScheme, + Scheme = "Bearer", + Reference = new() + { + Type = ReferenceType.SecurityScheme, + Id = IdentityConstants.BearerScheme + } + }; + options.AddDocumentTransformer((document, context, cancellationToken) => + { + document.Components ??= new(); + document.Components.SecuritySchemes.Add(IdentityConstants.BearerScheme, scheme); + return Task.CompletedTask; + }); + options.AddOperationTransformer((operation, context, cancellationToken) => + { + if (context.Description.ActionDescriptor.EndpointMetadata.OfType().Any()) + { + operation.Security = [new() { [scheme] = [] }]; + } + return Task.CompletedTask; + }); + return options; + } +} \ No newline at end of file diff --git a/Todo.Api/Program.cs b/Todo.Api/Program.cs index 17589fb..5a7d195 100644 --- a/Todo.Api/Program.cs +++ b/Todo.Api/Program.cs @@ -23,7 +23,7 @@ builder.Services.AddCurrentUser(); // Configure Open API -builder.Services.AddOpenApi(); +builder.Services.AddOpenApi(options => options.AddBearerTokenAuthentication()); // Configure rate limiting builder.Services.AddRateLimiting(); @@ -47,6 +47,7 @@ app.MapScalarApiReference(options => { options.Servers = []; + options.Authentication = new() { PreferredSecurityScheme = IdentityConstants.BearerScheme }; }); }