Skip to content

Commit a2c81a5

Browse files
committed
Cache JWKSClient property
The JWKSClient caches the keys from the given discovery keys endpoint, so this property should also be cached on the Authentication instance. Cache a couple of other properties we only need to create once per instance.
1 parent 6230bbc commit a2c81a5

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

manage_breast_screening/dicom/authentication.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import os
3+
from functools import cached_property
34

45
import jwt
56
from django.conf import settings
@@ -28,10 +29,10 @@ def _decode(self, token: str) -> dict | None:
2829
Checks the signature, audience, and issuer claims to ensure the token is valid and intended for this API.
2930
"""
3031
try:
31-
signing_key = self.jwks_client.get_signing_key_from_jwt(token).key
32+
signing_key = self.jwks_client.get_signing_key_from_jwt(token)
3233
payload = jwt.decode(
3334
token,
34-
signing_key,
35+
signing_key.key,
3536
algorithms=ALLOWED_ALGORITHMS,
3637
audience=self.audience,
3738
issuer=self.issuers,
@@ -48,7 +49,7 @@ def _decode(self, token: str) -> dict | None:
4849
except Exception:
4950
logger.exception("Unable to parse authentication token.")
5051

51-
@property
52+
@cached_property
5253
def jwks_client(self) -> jwt.PyJWKClient:
5354
"""
5455
Creates a PyJWKClient instance for fetching and caching the JWKS keys from Azure AD.
@@ -62,7 +63,7 @@ def jwks_client(self) -> jwt.PyJWKClient:
6263
lifespan=JWT_SET_CACHE_TTL_SECONDS,
6364
)
6465

65-
@property
66+
@cached_property
6667
def discovery_keys_url(self) -> str:
6768
return f"https://login.microsoftonline.com/{self.tenant_id}/discovery/v2.0/keys"
6869

@@ -80,7 +81,7 @@ def tenant_id(self) -> str | None:
8081
"""
8182
return os.getenv("TENANT_ID", "")
8283

83-
@property
84+
@cached_property
8485
def issuers(self) -> list:
8586
"""
8687
The expected issuer claim(s) in the JWT token. This should match the tenant ID and the Azure AD endpoints.

0 commit comments

Comments
 (0)