如何在请求的 header 中使用 Swashbuckle 设置多个 api 键

How to set multiple api Key with Swashbuckle in the request's header

我有一个 web api2 项目,我在其中实施了 swashbuckle 以测试和记录我的 web 服务。 我试图在 SwaggerDocsConfig 中为身份验证设置一个 apiKey 并且它有效,但是如果我想添加另一个 apiKey(apiKeyappId ) 我做不到。

我在 swagger doc 中读到这是可能的,但我不知道如何使用 swashbuckle 以这种方式配置 swagger 文档。

Swagger 文档应该如何

securityDefinitions:
  apiKey:
    type: apiKey
    in: header
    name: X-API-KEY
  appId:
    type: apiKey
    in: header
    name: X-APP-ID
security:
  - apiKey: []
    appId: []

当我在我的项目中启用 swagger 时,我试图简单地添加另一个 ApiKey(参见上面的代码),但它没有用。

    GlobalConfiguration.Configuration.EnableSwagger(swagger =>
            {
                swagger.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority).TrimEnd('/') + req.GetRequestContext().VirtualPathRoot.TrimStart('/'));
                swagger.PrettyPrint();
                c.SingleApiVersion("v1", "Project.WebApi");             
                swagger.ApiKey("apiKey") //First ApiKey
                    .Description("API Key Authentication")
                    .Name("Authorization")
                    .In("header");
                swagger.ApiKey("apiId") //Second ApiKey
                    .Description("API Key Authentication")
                    .Name("Authorization") //Same Schema
                    .In("header");                              
                swagger.IncludeXmlComments(string.Format(@"{0}\bin\Project.WebApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));
                swagger.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
            })
            .EnableSwaggerUi(swagger =>
            {
                swagger.DocumentTitle("Project API");               
                swagger.DocExpansion(DocExpansion.List);
                swagger.EnableDiscoveryUrlSelector();
                swagger.EnableApiKeySupport("Authorization", "header");
            });

是否可以使用 Swashbuckle 来完成,或者我必须注入一个 js 脚本并从 client-side 完成?

谢谢

我刚刚用 Swagger-Net 测试了这个,它似乎工作正常...
这是一个功能齐全的示例:

http://nhc-noaa.azurewebsites.net/swagger/ui/index?filter=&docExpansion=list
输入 apiKey 和 appId 后,curl 将如下所示:

curl -X GET "http://nhc-noaa.azurewebsites.net/api/Videos?count=1&frameRate=1&isCompressed=false" 
     -H "accept: application/json" -H "apiKey: 111" -H "appId: 222"

完全披露我是 Swagger-Net 的所有者,实现与 swashbuckle 非常相似,我只是尝试简化很多设置,EnableApiKeySupport 是我完全删除的其中一个,做什么你问你需要的是:

c.ApiKey("apiKey", "header", "API Key Authentication", typeof(KeyAuthorizeAttribute));
c.ApiKey("appId", "header", "APP ID Authentication", typeof(KeyAuthorizeAttribute));

完整代码在这里:
https://github.com/heldersepu/nhc-noaa/blob/master/nhc-noaa/App_Start/SwaggerConfig.cs

@HelderSepu 的回应有效,但我找到了另一种解决方案,也许可以帮助那些由于某种原因无法从 Swashbuckle 转移到 Swagger-Net 的人。

可以创建一个自定义的 OperationFilter 对象,您可以通过这种方式在每次调用中设置额外的参数:

public class AuthTokenHeaderParameter : IOperationFilter
{       
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
            operation.parameters = new List<Parameter>();

        var authorizeAttributes = apiDescription
            .ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();

        if (authorizeAttributes.ToList().Any(attr => attr.GetType() == typeof(AllowAnonymousAttribute)) == false)
        {
            operation.parameters.Add(new Parameter()
            {
                name = "ApiKey",
                @in = "header",
                type = "string",
                description = "Authorization Token. Please remember the Bearer part",
                @default = "Bearer ",
                required = true
            });
            operation.parameters.Add(new Parameter()
            {
                name = "AppId",
                @in = "header",
                type = "string",
                description = "AppId",
                required = true
            });
        }
    }
}

那你这样配置Swagger的时候就要实现了:

c.OperationFilter<AuthTokenHeaderParameter>();

希望这对某人有所帮助。