1- import time
21from typing import Annotated , Any , Optional
32
43import jwt
54from fastapi import Depends , HTTPException , Request , status
6- from fastapi .security import HTTPAuthorizationCredentials , HTTPBearer
5+ from fastapi .security import HTTPAuthorizationCredentials , HTTPBearer , SecurityScopes
76
87from common import AppConfig
98from http_app .dependencies import app_config
@@ -35,35 +34,21 @@ def _jwks_client(config: Annotated[AppConfig, Depends(app_config)]) -> jwt.PyJWK
3534 return jwt .PyJWKClient (config .AUTH .JWKS_URL )
3635
3736
38- class JWTBearer (HTTPBearer ):
39- async def __call__ (
40- self ,
41- request : Request ,
42- ) -> Optional [HTTPAuthorizationCredentials ]:
43- credentials = await super (JWTBearer , self ).__call__ (request )
44-
45- await self .decode (request )
37+ class JWTDecoder :
38+ """Does all the token verification using PyJWT"""
4639
47- return credentials
48-
49- async def decode (
40+ async def __call__ (
5041 self ,
51- request : Request ,
52- jwks_client : jwt .PyJWKClient = Depends (_jwks_client ),
42+ security_scopes : SecurityScopes ,
5343 config : AppConfig = Depends (app_config ),
54- ) -> dict [ str , Any ]:
55- credentials = await super ( JWTBearer , self ). __call__ ( request )
56-
57- if not credentials :
44+ jwks_client : jwt . PyJWKClient = Depends ( _jwks_client ),
45+ token : Optional [ HTTPAuthorizationCredentials ] = Depends ( HTTPBearer ()),
46+ ):
47+ if token is None :
5848 raise UnauthenticatedException ()
5949
60- if not credentials .scheme == "Bearer" :
61- raise UnauthorizedException ("Invalid authentication scheme." )
62-
6350 try :
64- signing_key = jwks_client .get_signing_key_from_jwt (
65- credentials .credentials
66- ).key
51+ signing_key = jwks_client .get_signing_key_from_jwt (token .credentials ).key
6752 except jwt .exceptions .PyJWKClientError as error :
6853 raise UnauthorizedException (str (error ))
6954 except jwt .exceptions .DecodeError as error :
@@ -73,7 +58,7 @@ async def decode(
7358 # TODO: Review decode setup and verifications
7459 # https://pyjwt.readthedocs.io/en/stable/api.html#jwt.decode
7560 payload = jwt .decode (
76- jwt = credentials .credentials ,
61+ jwt = token .credentials ,
7762 key = signing_key ,
7863 algorithms = [config .AUTH .JWT_ALGORITHM ],
7964 )
0 commit comments