# users/views_jwks.py from django.http import JsonResponse, HttpResponseNotFound from django.conf import settings import base64 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend def jwks_view(request): if settings.SIMPLE_JWT["ALGORITHM"] != "RS256": return HttpResponseNotFound("JWKS is only available in RS256 mode") public_key = settings.SIMPLE_JWT["VERIFYING_KEY"] key = serialization.load_pem_public_key( public_key.encode(), backend=default_backend() ) numbers = key.public_numbers() e = numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") n = numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") jwk = { "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "msa-user-key", "n": base64.urlsafe_b64encode(n).decode().rstrip("="), "e": base64.urlsafe_b64encode(e).decode().rstrip("="), } return JsonResponse({"keys": [jwk]})