aiohttp - before request for each API call

后端 未结 1 1894
别那么骄傲
别那么骄傲 2021-01-17 03:37

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

app = connexion.App(__name__, specification_dir=\'./swagger/\', sw         


        
1条回答
  •  离开以前
    2021-01-17 04:13

    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
    

    0 讨论(0)
提交回复
热议问题