将令牌授权装饰器添加到 swagger python 服务器存根端点的任何解决方法

any workaround to add token authorization decorator to endpoint at swagger python server stub

我知道如何保护 Flask 中的端点,我想对 swagger 生成的 python 服务器存根做同样的事情。我想知道如何为 swagger python 服务器集成 flask 令牌身份验证,以便端点得到保护。我可以轻松地将令牌身份验证装饰器添加到烧瓶中的端点。这就是 flask-restplus 中的工作原理,下面这个完全有效:

from flask import Flask, request, jsonify
from flask_restplus import Api, Resource

app = Flask(__name__)

authorizations = {
    'apikey' : {
        'type' : 'apiKey',
        'in' : 'header',
        'name' : 'X-API-KEY'
    },
}

api = Api(app, security = 'apikey',authorizations=authorizations)

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'X-API-KEY' in request.headers:
            token = request.headers['X-API-KEY']
        if not token:
            return {'message' : 'Token is missing.'}, 401
        if token != 'mytoken':
            return {'message' : 'Your token is wrong, wrong, wrong!!!'}, 401
        print('TOKEN: {}'.format(token))
        return f(*args, **kwargs)
    return decorated


 class classResource(Resource):
    @api.doc(security='apikey')
    @token_required
    def get(self):
        return "this is test"

如何在 swagger 生成的服务器存根中进行 Bearer 身份验证:

我想知道如何将此身份验证集成到 swagger 生成的 python 服务器存根中。以下是规范文件的开头:

openapi: 3.0.2
info:
    title: test api
    version: 1.0.0
servers:
- url: /api/v1/
  description: Example API Service
paths:
    /about:
        get:
            summary: general summary
            description: get current version
            responses:
                '200':
                    description: About information
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/version'
                '401':
                    description: Authorization information is missing or invalid.
components:
    securitySchemes:
        BearerAuth:
            scheme: bearer
            type: http
security:
    - BearerAuth: []

控制器大摇大摆 python 服务器存根:

更新:我的新尝试

这是由 swagger python 服务器存根生成的 default_controller,我尝试如下:

import connexion
import six

@api.doc(security='apikey')
@token_required
def about_get():  # noqa: E501
    return 'do some magic!'

但缺少 authorize 按钮。为什么?

in swagger python 服务器存根,我也有 authorization_controller 具有以下代码逻辑:

from typing import List

def check_BearerAuth(token):
    return {'test_key': 'test_value'}

更新:

这里是 swagger python 服务器存根。 about_get() 是一个端点,目前不安全。我们怎样才能像在烧瓶中那样确保它的安全?有什么想法吗?

如何在 swagger python 服务器存根中将上面的 flask 令牌身份验证添加到 about_get()?有什么办法吗?有什么想法吗?

更新

这是一个使用 JWT 作为承载格式的 yaml 示例: https://github.com/zalando/connexion/blob/master/examples/openapi3/jwt/openapi.yaml

生成flask server后,在swagger-ui上可以找到'Authorize'按钮。如果你在 'Authorize' 之前执行 /secret 你会得到一个 401 错误。

所以针对你的情况,你要改成:

openapi: 3.0.2
info:
    title: test api
    version: 1.0.0
servers:
- url: /api/v1/
  description: Example API Service
paths:
    /about:
        get:
            summary: general summary
            description: get current version
            security:
            - jwt: ['secret']
            responses:
                '200':
                    description: About information
                    content:
                        application/json:
                            schema:
                                type: string


components:
  securitySchemes:
    jwt:
      type: http
      scheme: bearer
      bearerFormat: JWT
      x-bearerInfoFunc: app.decode_token

因此,在您安装 connexion[swagger-ui] 并通过 python -m swagger_server 启动服务器后。然后,导航到http://0.0.0.0:8080/api/v1/ui/,您可以测试授权是否正常。如果您在授权前调用 /about,它将遇到 401 错误。


从代码添加身份验证:

from flask_restx import Api
authorizations = {
    'Bearer Auth': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'Authorization'
    },
}
api = Api(app, security='Bearer Auth', authorizations=authorizations)

顺便说一句,最好将 flask_restplus 迁移到 flask_restx,因为不再维护 flask_restplus。

来源

https://github.com/noirbizarre/flask-restplus/issues/398#issuecomment-444336893