我正在将具有使用Swashbuckle生成的Swagger文档的Web API从.NET Framework迁移到ASP.NET Core.在新的AspNetCore版本中,我使用的是Swashbuckle.AspNetCore v5.0.0-rc2.
I am migrating a Web API that has Swagger documenation generated using Swashbuckle from .NET Framework to ASP.NET Core. In the new AspNetCore version I'm using Swashbuckle.AspNetCore v5.0.0-rc2.
这是一项内部服务,身份验证使用自定义HTTP标头中提供的API密钥.在.NET Framework应用程序中,我将Swashbuckle配置为启用我的API密钥,如下所示:
This is an internal service and authentication uses an API key provided in a custom HTTP header. In the .NET Framework application, I configured Swashbuckle to enable my API key as follows:
c.ApiKey("apiKey") .Description("My description") .Name("MyHttpHeaderName") .In("header);和
c.EnableApiKeySupport("MyHtpHeaderName", "header);如何使用Swashbuckle.AspNetCore v5.0.0-rc2启用对同一API密钥的支持?
How can I enable support for the same API key using Swashbuckle.AspNetCore v5.0.0-rc2?
我通过搜索发现的许多信息似乎与v5.0.0-rc2之前的Swashbuckle.AspNetCode版本有关.
Much of the information I've found by searching seems to relate to versions of Swashbuckle.AspNetCode prior to v5.0.0-rc2.
此答案适用于v5.0.0-rc2,但仅涉及承载授权,似乎与使用自定义HTTP标头无关: stackoverflow/a/57872872/13087
This answer is for v5.0.0-rc2 but only covers Bearer Authorization, and doesn't seem to relate to using a custom HTTP header: stackoverflow/a/57872872/13087
推荐答案在Swashbuckle.AspNetCore中,授权设置全部由AddSecurityDefinition方法处理.
In Swashbuckle.AspNetCore, the authorization setup is all handled with the AddSecurityDefinition method.
在4.x中,您可以设置一个ApiKeyScheme来描述如何使用API密钥来授权请求:
In 4.x, you could set up an ApiKeyScheme that describes how to use an API key to authorize requests:
c.AddSecurityDefinition("ApiKey", new ApiKeyScheme() { Description = "My description", Name = "MyHttpHeaderName", In = "header", });从5.x开始,Swashbuckle.AspNetCore不再使用其自己的模型,而是依靠 .这意味着上面的安全性定义在5.x中看起来像这样:
Starting with 5.x, Swashbuckle.AspNetCore is no longer using its own models but instead relies on OpenAPI.NET. This means that the above security definition would look like this in 5.x:
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme() { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "MyHttpHeaderName", Description = "My description", });请注意,您还必须设置安全要求来配置哪些操作需要哪种安全定义.在5.x中,其语法如下所示:
Note that you will also have to set up security requirements to configure which security definition is required for what operations. In 5.x, the syntax for that will look like this:
c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] { } } });您可以在有关安全性定义和要求的文档.
更多推荐
如何使用Swashbuckle.AspNetCore v5.0.0
发布评论