首页 文章

如何在请求的 Headers 中设置多个api Key和Swashbuckle

提问于
浏览
1

我've a web api2 project, where I'已实现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脚本并从客户端执行?

谢谢

2 回答

  • 1

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

  • 2

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

    我希望这可以帮助别人 .

相关问题