2016-12-16 116 views
12

我在API中有一些端点 - /user/login,/products如何在Swagger UI中使用请求发送自定义标头?

在Swagger UI中,我发帖emailpassword/user/login,作为响应,我收到token字符串。

然后,我可以从响应中复制令牌,并希望将其作为Authorization头部值用于请求所有网址(如果存在),并以/products为例。

我应该在Swagger用户界面页面上的某个地方手动创建一个文本输入,然后在那里放置令牌并以某种方式注入请求中或者是否有工具以更好的方式管理它?

回答

13

您可以将标题参数添加到您的要求,扬鞭的UI将其显示为可编辑的文本框:

swagger: "2.0" 
info: 
    version: 1.0.0 
    title: TaxBlaster 
host: taxblaster.com 
basePath: /api 
schemes: 
- http 

paths: 

    /taxFilings/{id}: 

    get: 
     parameters: 
     - name: id 
     in: path 
     description: ID of the requested TaxFiling 
     required: true 
     type: string 
     - name: auth 
     in: header 
     description: an authorization header 
     required: true 
     type: string 
     responses: 
     200: 
      description: Successful response, with a representation of the Tax Filing. 
      schema: 
      $ref: "#/definitions/TaxFilingObject" 
     404: 
      description: The requested tax filing was not found. 

definitions: 
    TaxFilingObject: 
    type: object 
    description: An individual Tax Filing record. 
    properties: 
     filingID: 
     type: string 
     year: 
     type: string 
     period: 
     type: integer 
     currency: 
     type: string 
     taxpayer: 
     type: object 

Swagger-UI with auth param text box

您还可以apiKey类型添加安全定义:

swagger: "2.0" 
info: 
    version: 1.0.0 
    title: TaxBlaster 
host: taxblaster.com 
basePath: /api 
schemes: 
- http 

securityDefinitions: 
    api_key: 
    type: apiKey 
    name: api_key 
    in: header 
    description: Requests should pass an api_key header. 

security: 
- api_key: [] 

paths: 

    /taxFilings/{id}: 

    get: 
     parameters: 
     - name: id 
     in: path 
     description: ID of the requested TaxFiling 
     required: true 
     type: string 

     responses: 
     200: 
      description: Successful response, with a representation of the Tax Filing. 
      schema: 
      $ref: "#/definitions/TaxFilingObject" 
     404: 
      description: The requested tax filing was not found. 

definitions: 
    TaxFilingObject: 
    type: object 
    description: An individual Tax Filing record. 
    properties: 
     filingID: 
     type: string 
     year: 
     type: string 
     period: 
     type: integer 
     currency: 
     type: string 
     taxpayer: 
     type: object 

securityDefinitions对象定义了安全方案。

security对象(在Swagger-OpenAPI中称为“安全需求”)将安全方案应用于给定的上下文。在我们的例子中,我们通过将安全需求声明为最高级别来将其应用于整个API。我们可以选择在单独的路径项目和/或方法中覆盖它。

这将是ti指定您的安全方案的首选方式;它将取代第一个示例中的标题参数。不幸的是,Swagger-UI并没有提供一个文本框来控制这个参数,至少在我目前的测试中。

22

在ASP.net的WebAPI,最简单的方式来传递,在上扬鞭UI首标是实现应用(...)上IOperationFilter接口方法。

添加到您的项目:

public class AddRequiredHeaderParameter : 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 = "MyHeaderField", 
      @in = "header", 
      type = "string", 
      description = "My header field", 
      required = true 
     }); 
    } 
} 

SwaggerConfig.cs,从上面使用c.OperationFilter <牛逼>(注册过滤器)

public static void Register() 
    { 
     var thisAssembly = typeof(SwaggerConfig).Assembly; 

     GlobalConfiguration.Configuration 
      .EnableSwagger(c => 
      { 
       c.SingleApiVersion("v1", "YourProjectName"); 
       c.IgnoreObsoleteActions(); 
       c.UseFullTypeNameInSchemaIds(); 
       c.DescribeAllEnumsAsStrings(); 
       c.IncludeXmlComments(GetXmlCommentsPath()); 
       c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); 


       c.OperationFilter<AddRequiredHeaderParameter>(); // Add this here 
      }) 
      .EnableSwaggerUi(c => 
      { 
       c.DocExpansion(DocExpansion.List); 
      }); 
    } 
+1

嗨感谢分享这个,这是我所需要的。有没有一种方法可以禁用某些API方法?例如,用户登录不需要通过该标头,因为它返回Auth令牌。该添加的'MyHeaderField'是所有API方法Swagger文档。 –

+0

@NeilHodges你知道了吗?我甚至在寻找它。 –

+1

@ gee'K'iran您可以通过检查操作和apiDescription参数并选择添加标题来选择性地应用功能。 – Corcus

0

我结束因为我试图在Swagger UI中有条件地添加头文件参数,这是基于我添加到我的API方法中的我自己的[Authentication]属性。在@Corcus在评论中列出的提示之后,我能够得出我的解决方案,并希望它能帮助其他人。

使用反射,它检查嵌套在apiDescription中的方法是否具有所需的属性(MyApiKeyAuthenticationAttribute,在我的情况下)。如果是这样,我可以附加我想要的标题参数。

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


    var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor) 
     ((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo 
     .GetCustomAttributes(false); 
    if(attributes != null && attributes.Any()) { 
     if(attributes.Where(x => x.GetType() 
      == typeof(MyApiKeyAuthenticationAttribute)).Any()) { 

      operation.parameters.Add(new Parameter { 
       name = "MyApiKey", 
       @in = "header", 
       type = "string", 
       description = "My API Key", 
       required = true 
      }); 
      operation.parameters.Add(new Parameter { 
       name = "EID", 
       @in = "header", 
       type = "string", 
       description = "Employee ID", 
       required = true 
      }); 
     } 
    } 


} 
0

ASP.NET Core 2 Web API,使用Swashbuckle.AspNetCore包2.1.0,实现IDocumentFilter:

SwaggerSecurityRequirementsDocumentFilter.cs

using System.Collections.Generic; 
using Swashbuckle.AspNetCore.Swagger; 
using Swashbuckle.AspNetCore.SwaggerGen; 

namespace api.infrastructure.filters 
{ 
    public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter 
    { 
     public void Apply(SwaggerDocument document, DocumentFilterContext context) 
     { 
      document.Security = new List<IDictionary<string, IEnumerable<string>>>() 
      { 
       new Dictionary<string, IEnumerable<string>>() 
       { 
        { "Bearer", new string[]{ } }, 
        { "Basic", new string[]{ } }, 
       } 
      }; 
     } 
    } 
} 

在Startup.cs,配置安全定义和注册自定义过滤器:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddSwaggerGen(c => 
    { 
     // c.SwaggerDoc(..... 

     c.AddSecurityDefinition("Bearer", new ApiKeyScheme() 
     { 
      Description = "Authorization header using the Bearer scheme", 
      Name = "Authorization", 
      In = "header" 
     }); 

     c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>(); 
    }); 
} 

在Swagger UI中,点击授权按钮并为令牌设置值。

Window to set value

结果:

curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456" 
相关问题