【发布时间】:2020-03-25 15:43:08
【问题描述】:
我已经构建了一个使用 appid 和 apikey 进行身份验证的 API。当我使用 appid 和 apikey 从其他应用程序调用 API 时,它工作正常,但我在使用 /swagger URL 中的 API 函数时遇到问题。我可以在招摇 UI 的顶部输入一个 apikey,但我似乎无法在任何地方输入 appid。
我一直在查看其他类似的问题,并尝试了那里的建议。
我在 .Net Framework 4.7.2 Web API 应用程序上运行 Swashbuckle v5.6.0。
我已经添加了
c.ApiKey("apiKey")
.Description("API Key Authentication") // first key
.Name("Authorization")
.In("header");
c.ApiKey("appId")
.Description("API Key Authentication") // second key
.Name("Authorization")
.In("header");
致我的GlobalConfiguration.Configuration.EnableSwagger(c =>
和
c.EnableApiKeySupport("apiKey", "header");
c.EnableApiKeySupport("appId", "header");
致我的.EnableSwaggerUi(c =>
(都在 SwaggerConfig.cs 中)
当我从另一个应用程序调用 API 时,我使用的是 DelegatingHandler,它将 apiKey 和 appId 添加到 header 的 authorization 部分,那么调用函数时我想要做什么来自招摇的用户界面(例如http://my.api.com/myapi/swagger)。我已经看到有一种方法可以将授权按钮添加到 swagger UI 中,当您单击该按钮时,您可以添加 appId 之类的内容,但是如何在我的 swagger UI 中获取该按钮?或者有其他方法吗?
更新 1
我发现我需要实现 IOperationFilter,主要是因为它在 SwaggerConfig 的评论中这样说(d'oh!):
// you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
// according to your specific authorization implementation
public class AddRequiredAuthorizationHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = "appId",
@in = "header",
type = "string",
required = true,
schema = new Schema { @ref = "amx"},
description = "appID",
});
}
}
有了这个,我可以在调用函数时在 swagger UI 中添加 appId 键,并且顶部有一个 apiKey 字段,所以我认为这就是我所需要的。
但是,我似乎无法在 Authorization 标头上设置正确的架构(您可以在上面看到我尝试使用 schema = new Schema { @ref = "amx"} 将其设置为“amx”。当我提出请求然后检查我的 @ 987654332@ 不是我想要的“amx”,而是我打电话时输入的 appID,所以我的身份验证过程不批准它。
所以现在我只是想弄清楚如何将HttpAuthenticationContext.Request.Headers.Authorization.Scheme 设置为“amx”。
【问题讨论】:
标签: asp.net-web-api swagger swagger-ui swashbuckle .net-4.7.2