2017-04-17 55 views
11

我有一個Web API(ASP.NET核心),我正試圖調整這個招搖從它進行調用。 這些調用必須包含授權標頭,並且我使用承載認證。 來自Postman等第三方應用程序的電話會正常工作。 但我有問題設置標頭爲swagger(出於某種原因,我沒有收到標題)。這是怎麼看起來像現在:使用授權標頭(承載)設置Swagger(ASP.NET核心)

所有的
"host": "localhost:50352", 
    "basePath": "/" , 
    "schemes": [ 
    "http", 
    "https" 
    ], 
"securityDefinitions": { 
    "Bearer": { 
     "name": "Authorization", 
     "in": "header", 
     "type": "apiKey", 
     "description": "HTTP/HTTPS Bearer" 
    } 
    }, 
    "paths": { 
    "/v1/{subAccountId}/test1": { 
     "post": { 
     "tags": [ 
      "auth" 
     ], 
     "operationId": "op1", 
     "consumes": ["application/json", "application/html"], 
     "produces": ["application/json", "application/html"], 
     "parameters": [ 
      { 
      "name": "subAccountId", 
      "in": "path", 
      "required": true, 
      "type": "string" 
      } 
     ], 
     "security":[{ 
      "Bearer": [] 
     }], 
     "responses": { 
      "204": { 
      "description": "No Content" 
      }, 
      "400": { 
      "description": "BadRequest", 
      "schema": { 
       "$ref": "#/definitions/ErrorResponse" 
      } 
      }, 
      "401": { 
      "description": "Unauthorized", 
      "schema": { 
       "$ref": "#/definitions/ErrorResponse" 
      } 
      }, 
      "500": { 
      "description": "InternalServerError", 
      "schema": { 
       "$ref": "#/definitions/ErrorResponse" 
      } 
      } 
     }, 
     "deprecated": false 
     } 
    }, 

回答

21

首先,你可以使用Swashbuckle.AspNetCore NuGet包自動生成你的招搖定義。

你安裝包後,設置它Startup.cs的方法ConfigureServices

services.AddSwaggerGen(c => { 
c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { In = "header", Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = "apiKey" }); 

然後你可以在頁面的右上角使用授權按鈕。

至少你可以嘗試使用這個包來生成有效的招搖定義

+0

你的解釋爲我解決了這個問題。 –

+0

好的答案,但是當我用ABP樣板做這件事時,它不適用於Dynamic Web Api(https://aspnetboilerplate.com/Pages/Documents/Dynamic-Web-API) –

+2

@VadimK直到我升級到.NET Core 2.0 – monty

1

目前揚鞭具有與JWT令牌認證功能,並能自動添加令牌插入頭,我已經回答了here