最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net core - How do I enable Scalar to ask for an API Key in .Net 9? - Stack Overflow

programmeradmin1浏览0评论

I have 2 sets of controllers: internal and external

I have JWT auth on internals and API Key auth on externals.

How do I setup my API to enable Scalar to ask for API key but only for the external controllers?

I have 2 sets of controllers: internal and external

I have JWT auth on internals and API Key auth on externals.

How do I setup my API to enable Scalar to ask for API key but only for the external controllers?

Share Improve this question edited Mar 6 at 7:14 Zhi Lv 22k1 gold badge27 silver badges37 bronze badges asked Mar 3 at 17:05 NotLostRiderNotLostRider 972 silver badges6 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

This is how I enabled Scalar to ask for an API Key for the external set of controllers.

  1. Add a ApiKeySecuritySchemeTransformer class to your API project

  2. Apply the above class to AddOpenApi options.

  3. ApiKeySecuritySchemeTransformer.cs

internal sealed class ApiKeySecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
 {
     public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
     {
         var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();

         if (authenticationSchemes.Any(authScheme => authScheme.Name == "ApiKeyScheme"))
         {
             var requirements = new Dictionary<string, OpenApiSecurityScheme>
             {
                 ["API key"] = new OpenApiSecurityScheme
                 {
                     Type = SecuritySchemeType.ApiKey,
                     Scheme = "ApiKeyScheme",
                     In = ParameterLocation.Header,
                     Name = "X-API-KEY"
                 }
             };

             document.Components ??= new OpenApiComponents();
             document.Components.SecuritySchemes = requirements;

             foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations))
             {
                 operation.Value.Security.Add(new OpenApiSecurityRequirement
                 {
                     [new OpenApiSecurityScheme
                     {
                         Reference = new OpenApiReference
                         {
                             Id = "API key",
                             Type = ReferenceType.SecurityScheme
                         }
                     }] = Array.Empty<string>()
                 });
             }
         }
     }
 }

The first "API key" string is what shows in in the Auth drop down in Scalar:

The second "API key" string is what shows in the placeholder text next to Authentication:

  1. Add this line to options of AddOpenApi options.AddDocumentTransformer<ApiKeySecuritySchemeTransformer>();

For example:

 services.AddOpenApi("external", options =>
 {
     options.AddDocumentTransformer((document, context, _) =>
     {
         document.Info = new()
         {
             Title = "Open API V1",
             Version = "v1",
             Description =
                 """
                 API for creating and managing accounts and users.
                 Supports JSON responses.
                 """,
             Contact = new()
             {
                 Name = "API Support",
                 Email = "[email protected]",
                 Url = new Uri("https://api.example/support")
             }
         };

         return Task.CompletedTask;
     });

     options.ShouldInclude = (description) => description.RelativePath!.StartsWith("api/external");
     options.AddDocumentTransformer<ApiKeySecuritySchemeTransformer>();
发布评论

评论列表(0)

  1. 暂无评论