我正在将一个Web从.NET框架迁移到ASP.NET内核,该API具有使用Swashbuckle生成的Swagger文档。在新的AspNetCore版本中,我使用的是Swashbuckle.AspNetCore v5.0.0-rc2。
这是一个内部服务,身份验证使用自定义HTTP报头中提供的API密钥。在.NET框架应用程序中,我将配置为启用API密钥,如下所示:
c.ApiKey("apiKey")
.Description("My description")
.Name("MyHttpHeaderName")
.In("header);和
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
发布于 2019-09-15 12:56:06
在Swashbuckle.AspNetCore中,授权设置全部由AddSecurityDefinition方法处理。
在4.x中,您可以设置一个ApiKeyScheme,该描述如何使用API密钥授权请求:
c.AddSecurityDefinition("ApiKey", new ApiKeyScheme()
{
Description = "My description",
Name = "MyHttpHeaderName",
In = "header",
});从5.x开始,Swashbuckle.AspNetCore不再使用自己的模型,而是依赖于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://stackoverflow.com/questions/57943550
复制相似问题