使用授权标头(Bearer)设置Swagger(ASP.NET Core)

问题描述 投票:32回答:2

我有一个Web API(ASP.NET核心),我正在尝试调整swagger来进行调用。这些调用必须包含Authorization标头,我正在使用Bearer身份验证。来自Postman等第三方应用的电话也没问题。但我遇到了设置swagger标头的问题(由于某种原因我没有收到标头)。这就是现在的样子:

  "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
      }
    },
c# asp.net-core swagger-ui
2个回答
106
投票

首先,您可以使用Swashbuckle.AspNetCore nuget包自动生成您的swagger定义。 (在2.3.0上测试)

安装软件包后,在方法ConfigureServices中的Startup.cs中进行设置

        services.AddSwaggerGen(c => {
            c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
            c.AddSecurityDefinition("Bearer",
                new ApiKeyScheme { In = "header",
                  Description = "Please enter into field the word 'Bearer' following by space and JWT", 
                  Name = "Authorization", Type = "apiKey" });
            c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
                { "Bearer", Enumerable.Empty<string>() },
            });

        });

然后,您可以使用页面右上角的“授权”按钮。

至少你可以尝试使用这个包来生成有效的swagger定义


2
投票

目前Swagger具有使用JWT-token进行身份验证的功能,并且可以自动将标记添加到标头中,我已经回答了here

© www.soinside.com 2019 - 2024. All rights reserved.