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

2024-05-23

我正在将具有使用 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);

and

c.EnableApiKeySupport("MyHtpHeaderName", "header);

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

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

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


In Swashbuckle.AspNetCore,授权设置全部由AddSecurityDefinition method.

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

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

从 5.x 开始,Swashbuckle.AspNetCore不再使用自己的模型,而是依赖于OpenAPI.NET https://github.com/microsoft/OpenAPI.NET。这意味着上述安全定义在 5.x 中将如下所示:

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

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

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

您可以在以下位置阅读有关这一切的更多信息有关安全定义和要求的文档 https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/v5.0.0-rc2/README-v5.md#add-security-definitions-and-requirements.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐