From bbb027cd0d7002e29811750c521ecc4e6775a9bc Mon Sep 17 00:00:00 2001 From: Maxime Alves LIRMM Date: Thu, 2 Feb 2023 19:56:59 +0100 Subject: [PATCH] [authMiddleware][BREAKING] read token from "JWTToken" cookie --- halfapi/lib/jwt_middleware.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/halfapi/lib/jwt_middleware.py b/halfapi/lib/jwt_middleware.py index e5f771a..436ab9e 100644 --- a/halfapi/lib/jwt_middleware.py +++ b/halfapi/lib/jwt_middleware.py @@ -14,6 +14,7 @@ from os import environ import typing from uuid import UUID +from http.cookies import SimpleCookie import jwt from starlette.authentication import ( AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials, @@ -34,6 +35,15 @@ except FileNotFoundError: logger.error('Could not import SECRET variable from conf module,'\ ' using HALFAPI_SECRET environment variable') +def cookies_from_scope(scope): + cookie = dict(scope.get("headers") or {}).get(b"cookie") + if not cookie: + return {} + + simple_cookie = SimpleCookie() + simple_cookie.load(cookie.decode("utf8")) + return {key: morsel.value for key, morsel in simple_cookie.items()} + class JWTAuthenticationBackend(AuthenticationBackend): def __init__(self, secret_key: str = SECRET, algorithm: str = 'HS256', prefix: str = 'JWT'): @@ -53,7 +63,8 @@ class JWTAuthenticationBackend(AuthenticationBackend): ) -> typing.Optional[typing.Tuple['AuthCredentials', 'BaseUser']]: - token = conn.headers.get('Authorization') + token = cookies_from_scope(conn.scope).get('JWTToken') + is_check_call = 'check' in conn.query_params is_fake_user_id = is_check_call and 'user_id' in conn.query_params PRODUCTION = conn.scope['app'].debug == False