如何使用 Swashbuckle.AspNetCore v5.0.0-rc2 记录 API 密钥身份验证

Joe*_*Joe 3 swagger swashbuckle asp.net-core

我正在将具有使用 Swashbuckle 生成的 Swagger 文档的 Web API 从 .NET Framework 迁移到 ASP.NET Core。在新的 AspNetCore 版本中,我使用的是 Swashbuckle.AspNetCore v5.0.0-rc2。

这是一项内部服务,身份验证使用自定义 HTTP 标头中提供的 API 密钥。在 .NET Framework 应用程序中,我将 Swashbuckle 配置为启用我的 API 密钥,如下所示:

c.ApiKey("apiKey")
   .Description("My description")
   .Name("MyHttpHeaderName")
   .In("header);
Run Code Online (Sandbox Code Playgroud)

c.EnableApiKeySupport("MyHtpHeaderName", "header);
Run Code Online (Sandbox Code Playgroud)

如何使用 Swashbuckle.AspNetCore v5.0.0-rc2 启用对相同 API 密钥的支持?

我通过搜索找到的大部分信息似乎与 v5.0.0-rc2 之前的 Swashbuckle.AspNetCode 版本有关。

此答案适用于 v5.0.0-rc2,但仅涵盖承载授权,并且似乎与使用自定义 HTTP 标头无关:https : //stackoverflow.com/a/57872872/13087

pok*_*oke 18

在 中Swashbuckle.AspNetCore,授权设置都是通过该AddSecurityDefinition方法处理的。

在 4.x 中,你可以设置一个ApiKeyScheme描述如何使用 API 密钥来授权请求​​的:

c.AddSecurityDefinition("ApiKey", new ApiKeyScheme()
{
    Description = "My description",
    Name = "MyHttpHeaderName",
    In = "header",
});
Run Code Online (Sandbox Code Playgroud)

从 5.x 开始,Swashbuckle.AspNetCore不再使用自己的模型,而是依赖于OpenAPI.NET. 这意味着上面的安全定义在 5.x 中看起来像这样:

c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme()
{
    Type = SecuritySchemeType.ApiKey,
    In = ParameterLocation.Header,
    Name = "MyHttpHeaderName",
    Description = "My description",
});
Run Code Online (Sandbox Code Playgroud)

请注意,您还必须设置安全要求以配置哪些操作需要哪些安全定义。在 5.x 中,其语法如下所示:

c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" }
        },
        new string[] { }
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以在有关安全定义和要求文档中阅读有关所有这些内容的更多信息。