From 69127f1b4415b70432dce68014f73571b958c0fd Mon Sep 17 00:00:00 2001 From: Safia Abdalla Date: Wed, 27 Nov 2024 12:31:19 -0800 Subject: [PATCH] Add OpenAPI configuration for authentication (#99) --- .../Extensions/OpenApiOptionsExtensions.cs | 37 +++++++++++++++++++ Todo.Api/Program.cs | 3 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 Todo.Api/Extensions/OpenApiOptionsExtensions.cs 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 }; }); }