2016-12-16 159 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" 
相關問題