aiohttp-在每个API调用请求之前

时间:2019-11-15 22:52:21

标签: python python-asyncio swagger-ui aiohttp connexion

当我使用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身份验证吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您必须将 middleware_handler auth_through_token 中移出。

然后, 引用您的代码:

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': [middleware_handler]}

所以最终代码应如下所示:

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

@web.middleware
async def middleware_handler(request: web.Request, handler: Any) -> 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
相关问题