I’m working on a Django application that uses Authlib for JWT authentication, with Auth0 as the identity provider. I’m fetching the public key from the JWKS endpoint provided by Auth0 to validate the JWT. However, when decoding the token, I’m encountering the following error:
Error: AttributeError: 'NoneType' object has no attribute 'startswith'
This error occurs when processing the public key from the JWKS response. I suspect it might be an issue with how the key is fetched or decoded, particularly with the x5c field. I’m unsure how to handle this properly.
Here’s my current middleware implementation:
import os
import requests
from authlib.jose import JsonWebToken
from django.utils.deprecation import MiddlewareMixin
from rest_framework.exceptions import AuthenticationFailed
from dotenv import load_dotenv
# Load environment variables from the .env file
load_dotenv()
class Auth0Middleware(MiddlewareMixin):
def __init__(self, get_response=None):
self.get_response = get_response
self.jwt = JsonWebToken([os.getenv('ALGORITHMS', 'RS256')]) # Load algorithm from env
self.jwks_url = f"https://{os.getenv('AUTH0_DOMAIN')}/.well-known/jwks.json" # Load Auth0 domain from env
self.jwks = self.get_jwks()
def get_jwks(self):
response = requests.get(self.jwks_url)
if response.status_code == 200:
return response.json()
raise AuthenticationFailed("Failed to fetch JWKS")
def get_public_key(self, token):
try:
headers = self.jwt.decode(token, None, claims_cls=None)
kid = headers.get('kid')
for key in self.jwks['keys']:
if key['kid'] == kid:
raw_key = key.get('x5c', [])
if not raw_key or not isinstance(raw_key, list) or not raw_key[0]:
raise AuthenticationFailed("Invalid or missing x5c field in JWKS.")
return self.convert_to_pem(raw_key[0])
except Exception as e:
raise AuthenticationFailed(f"Error fetching public key: {str(e)}")
def convert_to_pem(self, raw_key):
return f"-----BEGIN CERTIFICATE-----n{raw_key}n-----END CERTIFICATE-----"```
Am I handling the public key extraction and JWT decoding correctly, or is there a better approach to prevent this error?
Gent Bytyqi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.