【问题标题】:How to set multiple api Key with Swashbuckle in the request's header如何在请求的标头中使用 Swashbuckle 设置多个 api Key
【发布时间】:2018-09-26 04:02:27
【问题描述】:

我有一个 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 脚本并从客户端执行?

谢谢

【问题讨论】:

  • 您使用的是什么版本的 Swashbuckle?
  • 当前可用的最新版本:5.6.0

标签: c# asp.net-web-api2 swagger api-key swashbuckle


【解决方案1】:

@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>();

我希望这可以帮助某人。

【讨论】:

    【解决方案2】:

    我刚刚用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

    【讨论】:

    • 现在不能测试了,明天试试。谢谢!
    • 请注意,此解决方案将 API 密钥添加为 独立 安全要求 - "security": [ { "apiKey":[] }, { "appId":[] } ]。这意味着客户端可以使用apiKeyappId。但是 OP 要求提供"security": [ { "apiKey":[], "appId":[] } ] - 在相同安全要求中 的两个 API 密钥。 (区别解释here。)
    • 好点@Helen!
    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2018-05-30
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多