没有授权标题

时间:2018-03-11 18:29:41

标签: c# .net asp.net-core swashbuckle

我正在创建一个ASP.NET Core 2.0 Web API,一切都运行得很好,但我遇到了Swashbuckle的问题。我已经为我的API添加了基本身份验证,并将基本方案启用为Swasbuckle:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        c.AddSecurityDefinition("Basic", new BasicAuthScheme { Description = "Basic authentication" });
    });

    services.AddMvc();
}

当我访问SwaggerUI时,一切正常,我看到授权方案,我可以添加用户名和密码。调用任何api时会出现问题,Authorization标头永远不会发送到API控制器。

我是否需要做其他任何事情才能告诉Swasbuckle它必须发送授权标题?

1 个答案:

答案 0 :(得分:3)

好的,最后我找到了遗漏的东西。您需要添加文档过滤器才能让Swashbuckle发送授权:

public class BasicAuthFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        var securityRequirements = new Dictionary<string, IEnumerable<string>>()
        {
            { "Basic", new string[] { } }
        };

        swaggerDoc.Security = new[] { securityRequirements };
    }
}

//In the Startup class...
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        c.AddSecurityDefinition("Basic", new BasicAuthScheme { Description = "Basic authentication" });
            c.DocumentFilter<BasicAuthFilter>();
    });

    services.AddMvc();
}