-
Notifications
You must be signed in to change notification settings - Fork 427
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add OpenAPI configuration for authentication (#99)
- Loading branch information
1 parent
2d890e8
commit 69127f1
Showing
2 changed files
with
39 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters