2016-12-16 46 views
12

Mam niektóre punkty końcowe w API - /user/login, /products.Jak wysyłać niestandardowe nagłówki z prośbami w interfejsie użytkownika Swagger?

W Swagger UI zamieścić email i password do /user/login i jako odpowiedź otrzymam token ciąg.

Następnie mogę skopiować token z odpowiedzi i chcę go użyć jako wartości nagłówkowej Authorization w żądaniach do wszystkich adresów URL, jeśli jest obecny, a do /products jako przykład.

Czy muszę ręcznie utworzyć wpis tekstowy na stronie interfejsu użytkownika przechwytywania, a następnie umieścić tam token i w jakiś sposób wprowadzić żądania lub czy istnieją narzędzia do lepszego zarządzania nim?

Odpowiedz

13

Możesz dodać parametr nagłówka do Państwa potrzeb, a Swagger-UI pokaże go jako pola tekstowego edycji:

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

Można również dodać definicję bezpieczeństwa z rodzaju 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 

Obiekt securityDefinitions definiuje schematy zabezpieczeń.

Obiekt security (zwany "wymaganiami bezpieczeństwa" w Swagger-OpenAPI) stosuje schemat zabezpieczeń do danego kontekstu. W naszym przypadku stosujemy go do całego API, deklarując wymóg bezpieczeństwa na najwyższym poziomie. Możemy opcjonalnie zastąpić go w ramach poszczególnych elementów ścieżki i/lub metod.

Byłby to preferowany sposób, w jaki należy określić swój system zabezpieczeń; i zastępuje parametr nagłówka z pierwszego przykładu. Niestety, Swagger-UI nie oferuje pola tekstowego do kontrolowania tego parametru, przynajmniej w moich testach.

22

Na ASP.net WebAPI, najprostszym sposobem, aby przejść w nagłówku na Swagger UI jest wdrożenie Zastosuj (...) sposób na IOperationFilter interfejsu.

Dodaj do tego projektu:

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 
     }); 
    } 
} 

Na SwaggerConfig.cs, zarejestruj filtr od góry za pomocą 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

Cześć dzięki za dzielenie się tym, że to właśnie to, co potrzebne. Czy istnieje sposób wyłączenia go dla niektórych metod API? Na przykład logowanie użytkownika nie wymagałoby przekazania nagłówka jako zwrócenia tokena autoryzacji. Ten dodatek jest "MyHeaderField" do wszystkich metod API dokumentów Swagger. –

+0

@NeilHodges to wymyśliłeś. Nawet tego szukam. –

+1

@ gee'K'iran Możesz selektywnie zastosować tę funkcjonalność, sprawdzając parametry operacji i apiDescription i wybierając opcję dodania nagłówka. – Corcus

0

skończyło tutaj, ponieważ próbowałem warunkowo dodać parametry nagłówka w interfejsie użytkownika Swagger, w oparciu o mój własny atrybut [Authentication] dodany do mojej metody API. Podążając za wskazówką, że @Corcus znalazł się w komentarzu, udało mi się wyprowadzić moje rozwiązanie i mam nadzieję, że pomoże innym.

Używając Reflection, sprawdza, czy metoda zagnieżdżona w apiDescription ma żądany atrybut (MyApiKeyAuthenticationAttribute, w moim przypadku). Jeśli tak, mogę dołączyć moje pożądane parametry nagłówka.

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

W ASP.NET Core 2 Web API korzystając Swashbuckle.AspNetCore pakiet 2.1.0, wdrożenie 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[]{ } }, 
       } 
      }; 
     } 
    } 
} 

W Startup.cs skonfigurować definicję bezpieczeństwa i zarejestrować filtr niestandardowy:

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

W interfejsie użytkownika Swagger kliknij przycisk Autoryzuj i ustaw wartość tokena.

Window to set value

Wynik:

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