将JWT承载授权添加到NSwag 13

时间:2019-08-16 21:49:41

标签: c# .net-core swagger nswag

我们正在使用NSwag 11并尝试移至第13个,它似乎使用了完全不同的调用。

老式代码看起来像

public static class SwaggerServiceExtensions
{
    public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1.0", new Info { Title = "Main API v1.0", Version = "v1.0" });

            c.AddSecurityDefinition("Bearer", new ApiKeyScheme
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = "header",
                Type = "apiKey"
            });
        });

        return services;
    }

    public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Versioned API v1.0");

            c.DocExpansion("none");
        });

        return app;
    }
}

现在感觉库已经发生了很大的变化。因此,现在我将使用 services.AddSwaggerDocument app.UseSwaggerUi3 。并且没有其他选项,例如 SwaggerSecurityScheme ApiKeyScheme

1 个答案:

答案 0 :(得分:0)

您尝试过以下吗?

services.AddOpenApiDocument(document => 
{
    document.DocumentName = "v1";
    document.PostProcess = d =>
    {
        d.Info.Version = "v1";
        d.Info.Title = "Main API v1.0";
    };

    document.AddSecurity("apikey", Enumerable.Empty<string>(), new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Type = OpenApiSecuritySchemeType.ApiKey,
        Name = "Authorization",
        In = OpenApiSecurityApiKeyLocation.Header
    });

    document.OperationProcessors.Add(
        new OperationSecurityScopeProcessor("bearer"));
});

使用

app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
        settings.DocumentPath = "/swagger/" + "v1" + "/swagger.json";
        settings.DocExpansion = "none";
});