Skip to content

Commit

Permalink
Add OpenAPI configuration for authentication (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
captainsafia authored Nov 27, 2024
1 parent 2d890e8 commit 69127f1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
37 changes: 37 additions & 0 deletions Todo.Api/Extensions/OpenApiOptionsExtensions.cs
Original file line number Diff line number Diff line change
@@ -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<IAuthorizeData>().Any())
{
operation.Security = [new() { [scheme] = [] }];
}
return Task.CompletedTask;
});
return options;
}
}
3 changes: 2 additions & 1 deletion Todo.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -47,6 +47,7 @@
app.MapScalarApiReference(options =>
{
options.Servers = [];
options.Authentication = new() { PreferredSecurityScheme = IdentityConstants.BearerScheme };
});
}

Expand Down

0 comments on commit 69127f1

Please sign in to comment.