MetaCell / cloud-harness

Other
14 stars 5 forks source link

Fastapi generated api do not get authentication parameters from Cookie #583

Open filippomc opened 2 years ago

filippomc commented 2 years ago

The generated function supports the bearer token but not cookie.

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # retrieve the bearer token from the header
    # and save it for use in the AuthClient
    authorization = request.headers.get('Authorization')
    if authorization:
        set_authentication_token(authorization)

    return await call_next(request)

The cookie authentication is handy when the application is secured by a gatekeeper, as it comes for free on every request.

It's also ignoring the parameter coming from the spec, like in

  securitySchemes:
    bearerAuth:
      scheme: bearer
      bearerFormat: JWT
      type: http
      x-bearerInfoFunc: cloudharness.auth.decode_token
    cookieAuth:
      type: apiKey
      name: kc-access
      in: cookie
      x-apikeyInfoFunc: cloudharness.auth.decode_token

This is not necessarily required as we don't have different decode token handlers, but can be confusins as the Connexion apis require those instead

filippomc commented 2 years ago

To use the cookie in place of the Bearer can change the main.jinja2 template to use the APIKeyCookie in place of the Bearer authentication

Relevant code:

...
from fastapi.security import APIKeyCookie, HTTPBasicCredentials
...
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # retrieve the bearer token from the header
    # and save it for use in the AuthClient
    authorization = request.headers.get('Authorization') or request.cookies.get(
        'kc-access'
    )
    if authorization:
        if "Bearer" in authorization:
            authorization = authorization.split("Bearer ")[1]
        set_authentication_token(authorization)
    return await call_next(request)
security = APIKeyCookie(name="kc-access")