3

我正在运行一个烧瓶应用程序并使用 flasgger 生成 Swagger Specs 以及 Swagger UI。我的 API 要求使用不记名令牌对请求进行身份验证。我能够获取页面上的按钮并设置令牌。但它不是通过请求发送的。我正在使用 OpenAPI 3.0.3。下面是我的代码:

from flasgger import Swagger

swagger_template = {
    'components': {
        'securitySchemes': {
            'bearerAuth': {
                'type': 'http',
                'scheme': 'bearer',
                'bearerFormat': 'JWT'
            }
        },
        'security': {
            'bearerAuth': []
        }
    }
}

# Register controllers
api = Api(app)
swagger = Swagger(app=app, config={
    'headers': [

    ],
    'title': 'Model Design Application API',
    'specs': [
        {
            'endpoint': 'apispec',
            'route': '/apispec.json'
        }
    ],
    'openapi': '3.0.3'
}, template=swagger_template)

这是要在 Swagger UI 中设置的令牌:

在此处输入图像描述

这是我在 Swagger 中获得的 UI:

在此处输入图像描述

这是生成的 apispec.json:

{
  "definitions": {
    "User": {
      "properties": {
        "username": {
          "default": "Steven Wilson", 
          "description": "The name of the user", 
          "type": "string"
        }
      }
    }
  }, 
  "info": {
    "description": "powered by Flasgger", 
    "termsOfService": "/tos", 
    "title": "Model Design Application API", 
    "version": "0.0.1"
  }, 
  "openapi": "3.0.3", 
  "paths": {
    "/profile": {
      "get": {
        "description": "It works also with swag_from, schemas and spec_dict<br/>", 
        "responses": {
          "200": {
            "description": "A single user item", 
            "schema": {
              "$ref": "#/definitions/User"
            }
          }
        }, 
        "summary": "This examples uses FlaskRESTful Resource"
      }
    }
  }, 
  "security": {
    "bearerAuth": []
  }, 
  "securitySchemes": {
    "bearerAuth": {
      "bearerFormat": "JWT", 
      "scheme": "bearer", 
      "type": "http"
    }
  }
}

请指教。任何帮助表示赞赏。

4

1 回答 1

2

要在 Flasgger API 中添加标头,请执行以下更改:

SWAGGER_TEMPLATE = {"securityDefinitions": {"APIKeyHeader": {"type": "apiKey", "name": "x-access-token", "in": "header"}}}

swagger = Swagger(app, template=SWAGGER_TEMPLATE)

这里,x-access-token是我们在 header 中的键名。您可以根据需要更改此名称。之后,我们需要在 .yml 文件中添加这个头文件。我们的 .yml 文件将如下所示:

summary: "Put your summery here."
description: "Put your description here."
consumes:
- "application/json"
produces:
- "application/json"
security:
- APIKeyHeader: ['x-access-token']
responses:
  200:
    description: "Success"
于 2020-12-17T05:36:16.140 回答