aiohttp-请求每个API调用之前

问题描述 投票:0回答:1

当我使用Flask时,每个API调用都会在处理之前经过身份验证:

app = connexion.App(__name__, specification_dir='./swagger/', swagger_json=True, swagger_ui=True, server='tornado')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'ABCD API'})
# add CORS support
CORS(app.app)
@app.app.before_request
def before_request_func():
    app_id = request.headers.get("X-AppId")
    token = request.headers.get("X-Token")
    user, success = security.Security().authorize(token)
    if not success:
        status_code = 401
        response = {
            'code': status_code,
            'message': 'Unauthorized user'
        }
        return jsonify(response), status_code
    g.user = user

当我将其更改为AioHttp时,身份验证未正确设置:

options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
async def auth_through_token(app: web.Application, handler: Any) -> Callable:
    @web.middleware
    async def middleware_handler(request: web.Request) -> web.Response:
        headers = request.headers
        x_auth_token = headers.get("X-Token")
        app_id = headers.get("X-AppId")
        user, success = security.Security().authorize(x_auth_token)
        if not success:
            return web.json_response(status=401, data={
                "error": {
                    "message": ("Not authorized. Reason: {}"
                                )
                }
            })
        response = await handler(request)
        return response

    return middleware_handler


我的请求没有重定向到API方法。

任何人都可以帮助我为每个API设置我的before_request身份验证吗?谢谢。

python python-asyncio swagger-ui aiohttp connexion
1个回答
0
投票
引用您的代码:

options = {'swagger_path': 'swagger/', "swagger_ui": True} app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options) app.add_api('swagger.yaml', arguments={'title': ' ABCD API'}) app = web.Application(middlewares=[auth_through_token])

您必须

删除最后一行并将第一行更改为:

options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [auth_through_token]}
© www.soinside.com 2019 - 2024. All rights reserved.