Skip to content

Commit

Permalink
Replaced python-jose with PyJWT
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesstottmoj committed Dec 20, 2024
1 parent 22ea8ec commit e481e79
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 33 deletions.
6 changes: 3 additions & 3 deletions controlpanel/api/jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# First-party/Local
from controlpanel.api.models import User
from controlpanel.jwt import JWT, JWTDecodeError
from controlpanel.jwt import JWT, DecodeError

M2M_CLAIM_FLAG = "client-credentials"

Expand Down Expand Up @@ -69,7 +69,7 @@ def authenticate(self, request):
else:
try:
jwt.validate()
except JWTDecodeError:
except DecodeError:
return None

return self._get_client(jwt), None
Expand All @@ -89,7 +89,7 @@ def _get_client(self, jwt):
return AuthenticatedServiceClient(jwt.payload)
else:
raise exceptions.AuthenticationFailed()
except JWTDecodeError:
except DecodeError:
raise exceptions.AuthenticationFailed(
"Failed to be authenticated due to JWT decoder error!"
)
Expand Down
41 changes: 12 additions & 29 deletions controlpanel/jwt.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
# Third-party
import requests
import jwt
import structlog
from django.conf import settings
from jose import jwt
from jose.exceptions import JWTError
from requests.exceptions import RequestException
from jwt.exceptions import DecodeError, InvalidTokenError, PyJWKClientError
from rest_framework import HTTP_HEADER_ENCODING

log = structlog.getLogger(__name__)


class JWTDecodeError(Exception):
pass


class JWT:
def __init__(self, raw_token):
self._header = None
Expand All @@ -25,7 +19,7 @@ def __init__(self, raw_token):
"algorithms": [settings.OIDC_RP_SIGN_ALGO],
"audience": settings.OIDC_CPANEL_API_AUDIENCE,
"options": {
"require_sub": True,
"require": ["sub"],
},
}

Expand All @@ -37,30 +31,19 @@ def header(self):
if not self._header:
try:
self._header = jwt.get_unverified_header(self._raw_token)
except jwt.JWTError:
except (DecodeError, InvalidTokenError):
return None
return self._header

@property
def jwk(self):
if not self._jwk and self.header:
try:
response = requests.get(self.jwks_url, verify=False)
response.raise_for_status()
except RequestException as error:
raise JWTDecodeError(f"Failed fetching JWK: {error}")

jwks = response.json()
jwks_client = jwt.PyJWKClient(self.jwks_url)
self._jwk = jwks_client.get_signing_key_from_jwt(self._raw_token).key

for jwk in jwks.get("keys", []):
if jwk["kid"] == self.header["kid"]:
self._jwk = jwk
return self._jwk

raise JWTDecodeError(
f'No JWK with id {self.header["kid"]} found at {self.jwks_url} '
f"while decoding {self._raw_token}"
)
except PyJWKClientError as error:
raise DecodeError(f"Failed fetching JWK: {error}")

return self._jwk

Expand All @@ -73,8 +56,8 @@ def payload(self):
key=self.jwk,
**self.decode_options,
)
except (JWTError, KeyError) as error:
raise JWTDecodeError(f"Failed decoding JWT: {error}")
except (DecodeError, KeyError) as error:
raise DecodeError(f"Failed decoding JWT: {error}")
return self._payload

def validate(self):
Expand All @@ -84,8 +67,8 @@ def validate(self):
key=self.jwk,
**self.decode_options,
)
except (JWTError, KeyError) as error:
raise JWTDecodeError(f"Failed decoding JWT: {error}")
except (DecodeError, KeyError) as error:
raise DecodeError(f"Failed decoding JWT: {error}")

@classmethod
def from_auth_header(cls, request):
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ model-bakery==1.17.0
moto[all]==5.0.18
mozilla-django-oidc==4.0.1
psycopg2-binary==2.9.9
PyJWT==2.10.1
PyNaCl==1.5.0
pytest==8.0.0
pytest-django==4.9.0
python-dotenv==1.0.1
python-jose==3.3.0
pyyaml==6.0.2
rules==3.3
sentry-sdk==2.19.2
Expand Down

0 comments on commit e481e79

Please sign in to comment.