Skip to content

Commit

Permalink
Add time-based caching for JWKS fetching (#3586)
Browse files Browse the repository at this point in the history
  • Loading branch information
cmintey committed May 12, 2024
1 parent dc47145 commit 3f26328
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions mealie/core/security/providers/openid_provider.py
@@ -1,3 +1,4 @@
import time
from datetime import timedelta
from functools import lru_cache

Expand Down Expand Up @@ -82,7 +83,7 @@ async def authenticate(self) -> tuple[str, timedelta] | None:
def get_claims(self, settings: AppSettings) -> JWTClaims | None:
"""Get the claims from the ID token and check if the required claims are present"""
required_claims = {"preferred_username", "name", "email", settings.OIDC_USER_CLAIM}
jwks = OpenIDProvider.get_jwks()
jwks = OpenIDProvider.get_jwks(self.get_ttl_hash()) # cache the key set for 30 minutes
if not jwks:
return None

Expand Down Expand Up @@ -115,8 +116,9 @@ def get_claims(self, settings: AppSettings) -> JWTClaims | None:

@lru_cache
@staticmethod
def get_jwks() -> KeySet | None:
"""Get the key set from the open id configuration"""
def get_jwks(ttl_hash=None) -> KeySet | None:
"""Get the key set from the openid configuration"""
del ttl_hash # ttl_hash is used for caching only
settings = get_app_settings()

if not (settings.OIDC_READY and settings.OIDC_CONFIGURATION_URL):
Expand Down Expand Up @@ -145,3 +147,6 @@ def get_jwks() -> KeySet | None:
response.raise_for_status()
session.close()
return JsonWebKey.import_key_set(response.json())

def get_ttl_hash(self, seconds=1800):
return time.time() // seconds

0 comments on commit 3f26328

Please sign in to comment.