Skip to content

Commit 31bb0c4

Browse files
authored
Improve logging (#101)
1 parent 00c78af commit 31bb0c4

File tree

3 files changed

+380
-906
lines changed

3 files changed

+380
-906
lines changed

fastapi_jwks/validators/jwks_validator.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from functools import cached_property
23
from typing import Any, Generic, TypeVar
34

@@ -6,11 +7,12 @@
67
from cachetools import TTLCache, cached
78
from fastapi import HTTPException
89
from jwt import algorithms
9-
from loguru import logger
1010
from pydantic import BaseModel
1111

1212
from fastapi_jwks.models.types import JWKSConfig, JWTDecodeConfig
1313

14+
logger = logging.getLogger("fastapi-jwks")
15+
1416
DataT = TypeVar("DataT", bound=BaseModel)
1517

1618

@@ -41,10 +43,7 @@ def jwks_data(self) -> dict[str, Any]:
4143

4244
@staticmethod
4345
def __extract_algorithms(jwks_response: dict[str, Any]) -> list[str]:
44-
if "keys" not in jwks_response:
45-
raise ValueError("JWKS response does not contain keys")
46-
keys = jwks_response["keys"]
47-
return [key["alg"] for key in keys]
46+
return [key["alg"] for key in jwks_response["keys"]]
4847

4948
@cached_property
5049
def __is_generic_passed(self):
@@ -63,7 +62,11 @@ def validate_token(self, token: str) -> DataT:
6362
header = jwt.get_unverified_header(token)
6463
kid = header["kid"]
6564
jwks_data = self.jwks_data()
66-
if header["alg"] not in self.__extract_algorithms(jwks_data):
65+
provided_algorithms = self.__extract_algorithms(jwks_data)
66+
if header["alg"] not in provided_algorithms:
67+
logger.debug(
68+
f"Could not find '{header['alg']}' in provided algorithms: {provided_algorithms}"
69+
)
6770
raise HTTPException(status_code=401, detail="Invalid token")
6871
for key in jwks_data["keys"]:
6972
if key["kid"] == kid:
@@ -72,6 +75,9 @@ def validate_token(self, token: str) -> DataT:
7275
].from_jwk(key)
7376
break
7477
if public_key is None:
78+
logger.debug(
79+
f"No public key for provided algorithm '{header['alg']}' found in JWKS data"
80+
)
7581
raise HTTPException(status_code=401, detail="Invalid token")
7682
return self.__orig_class__.__args__[0].model_validate( # type: ignore
7783
# This line gets the generic value in runtime to transform it to the correct pydantic model
@@ -83,6 +89,8 @@ def validate_token(self, token: str) -> DataT:
8389
)
8490
)
8591
except jwt.ExpiredSignatureError:
92+
logger.debug("Expired token", exc_info=True)
8693
raise HTTPException(status_code=401, detail="Token has expired") from None
8794
except jwt.InvalidTokenError:
95+
logger.debug("Invalid token", exc_info=True)
8896
raise HTTPException(status_code=401, detail="Invalid token") from None

0 commit comments

Comments
 (0)