繁体   English   中英

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

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

我知道如何保护 flask 中的端点,我想对 swagger 生成的 python 服务器存根执行相同的操作。 我想知道如何为 swagger python 服务器集成 flask 令牌身份验证,以便端点得到保护。 我可以轻松地将令牌身份验证装饰器添加到 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 服务器存根中。 以下是 spec 文件的开头:

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: []

controller 在 swagger 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按钮。 为什么?

在 swagger python 服务器存根中,我还有具有以下代码逻辑的authorization_controller

from typing import List

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

更新

在 swagger python 服务器存根中。 about_get()是一个端点,目前不安全。 我们如何才能像在 flask 中所做的那样确保它的安全? 任何想法?

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

更新

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

生成 flask 服务器后,在 swagger-ui 上可以找到“授权”按钮。 如果您在“授权”之前执行 /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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM