簡體   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