aiohttp - before request for each API call

2020-03-31 07:00发布

问题:

When I was using Flask, every API call is authenticated before processed:

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

When I changed it to AioHttp, my authentication is not properly setup:

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


My request is not getting redirected to the API method.

Could anyone please help me to set up, my before_request authentication for every API? Thanks.

回答1:

Firstly, you have to move middleware_handler out from auth_through_token.

Then, Quote your code:

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])

You have to remove the last line and change the first line to:

options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [middleware_handler]}

So finally the code should look like:

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