2016-12-16 8 views
12

У меня есть некоторые конечные точки в API - /user/login, /products.Как отправить пользовательские заголовки с запросами в пользовательский интерфейс Swagger?

В Swagger UI я пост email и password к /user/login и в качестве ответа я получаю token строку.

Затем я могу скопировать маркер из ответа и хочу использовать его как значение Authorization заголовка в запросах ко всем URL-адресам, если он присутствует, и к /products в качестве примера.

Должен ли я вручную вводить текстовый ввод где-то на странице интерфейса Swagger, а затем помещать туда токен и как-то вводить в запросы или есть инструменты для управления им лучше?

ответ

13

Вы можете добавить параметр заголовка к вашему запросу, и Форс-интерфейс покажет, как редактируемое текстовое поле:

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, объявив требование безопасности верхним уровнем. Мы можем опционально переопределить его в отдельных элементах пути и/или методах.

Это будет предпочтительный способ указать вашу схему безопасности; и он заменяет параметр заголовка из первого примера. К сожалению, Swagger-UI не предлагает текстовое поле для управления этим параметром, по крайней мере, в моем тестировании.

22

На ASP.net WebAPI, простейший способ передать в заголовке на Swagger 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 <T>():

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, основываясь на моем собственном атрибуте [Authentication], который я добавил в свой метод API. Следуя намеку на то, что @Corcus указан в комментарии, я смог получить свое решение, и, надеюсь, это поможет другим.

Используя Reflection, он проверяет, имеет ли метод, вложенный в 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 нажмите кнопку Авторизация и установите значение для токена.

Window to set value

Результат:

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