Flasger添加承载授权

2024-06-16 10:14:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个flask应用程序,并使用Flasger生成招摇过市的规格以及招摇过市的用户界面。我的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中设置的令牌:

enter image description here

这是我大摇大摆地使用的UI:

enter image description here

这是生成的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"
    }
  }
}

请给我一些建议。感谢您的帮助


Tags: fromapiapphttptypeswaggertemplatedescription
1条回答
网友
1楼 · 发布于 2024-06-16 10:14:04

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

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

swagger = Swagger(app, template=SWAGGER_TEMPLATE)

这里,x-access-token是标题中的密钥名。您可以根据需要更改此名称。 在此之后,我们需要在.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"

相关问题 更多 >