过渡到Swashbuckle 5.0

时间:2019-07-11 01:34:09

标签: swagger swashbuckle

我正在通过Swashbuckle V4使用Swagger,并通过使用API​​ KEY对端点进行了身份验证。

在使用Swashbuckle V4时,以下配置非常有效(请注意,仅显示Swagger代码):

public void ConfigureServices(IServiceCollection services) {

 services.AddSwaggerGen(c => {
  c.SwaggerDoc(
   "v1",
   new Info {
    Title = "OAPI", Version = "v1"
   });
  c.AddSecurityDefinition("api_key", new ApiKeyScheme {
    In = "query",
    Description = "Please Enter Authentication Token",
    Name = "key",
    Type = "apiKey"
  });
  c.AddSecurityRequirement(new Dictionary < string, IEnumerable < string >> {
   {
    "api_key",
    new [] {
     "readAccess",
     "writeAccess"
    }
   }
  });
 });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

 app.UseSwagger();

 app.UseSwaggerUI(c => {
  c.SwaggerEndpoint("/api/swagger/v1/swagger.json", "API V1");
  c.RoutePrefix = "api/swagger";
 });
}

Swashbuckle GitHub page包含一个“ 过渡到Swashbuckle 5.0 ”主题,但未涵盖API密钥的使用。

我无法找到有关如何过渡到V5的完整示例,因此我分析了Method签名以产生相同的配置。

以下代码伪装成复制上述V4配置:

public void ConfigureServices(IServiceCollection services) {

 var securityScheme = new OpenApiSecurityScheme {
   In = ParameterLocation.Query,
   Description = "Please Enter Authentication Token",
   Name = "key",
   Type = SecuritySchemeType.ApiKey
 };

 services.AddSwaggerGen(c => {
  c.SwaggerDoc("V1", new OpenApiInfo {
    Version = "V1",
    Title = "API",
    Description = "API"
  });

  c.AddSecurityDefinition("api_key", securityScheme);

  c.AddSecurityRequirement(new OpenApiSecurityRequirement {
   {
    securityScheme,
    new [] {
     "readAccess",
     "writeAccess"
    }
   }
  });

  c.EnableAnnotations();
 });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

 app.UseSwagger();

 app.UseSwaggerUI(c => {
  c.SwaggerEndpoint("/api/swagger/v1/swagger.json", "API V1");
  c.RoutePrefix = "api/swagger";
 });
}

运行API时,将显示Swagger身份验证窗口,我可以使用API​​密钥进行身份验证。

不幸的是,执行任何端点时,我收到以下错误:

 System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.

        at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync
        at Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync]
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync
        at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync
        at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke
        at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke
        at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke
        at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke
        at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke
        at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore

我认为我缺少一些东西,我已经尝试研究 Microsoft.OpenApi.Models 类,但是到目前为止我还没有运气。它可能是一个很小的细节,但到目前为止还无法理解...

2 个答案:

答案 0 :(得分:2)

使用AddSecurityRequirement时需要引用该方案,因为您是全局应用它。 同样,当使用除“ oauth2”以外的任何其他类型时,作用域数组也必须为空。

下面的示例应该起作用。

c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id = "api_key",
                                Type = ReferenceType.SecurityScheme
                            }
                        },
                        new List<string>() }
                });

答案 1 :(得分:0)

除了执行@Pavlos所说的以外,您还需要使用AddAuthentication(string defaultScheme)指定默认的authenticationScheme。 例如:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

或在RequireAuthorization方法中指定authorizeData。

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers()
        .RequireAuthorization(new AuthorizeAttribute() { AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme });
});

,您可以使用多个AuthenticationSchemes,并以逗号将它们加入。