authentik.providers.oauth2.views.jwks
authentik OAuth2 JWKS Views
1"""authentik OAuth2 JWKS Views""" 2 3from base64 import b64encode, urlsafe_b64encode 4from collections.abc import Generator 5from typing import Literal 6 7from cryptography.hazmat.primitives import hashes 8from cryptography.hazmat.primitives.asymmetric.ec import ( 9 SECP256R1, 10 SECP384R1, 11 SECP521R1, 12 EllipticCurvePublicKey, 13) 14from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PublicKey 15from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey 16from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey 17from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes 18from cryptography.hazmat.primitives.serialization import Encoding 19from cryptography.x509 import Certificate 20from django.http import Http404, HttpRequest, HttpResponse, JsonResponse 21from django.views import View 22from jwt.utils import base64url_encode 23 24from authentik.core.models import Application 25from authentik.crypto.models import CertificateKeyPair 26from authentik.lib.jwt_mldsa import MLDSAKey 27from authentik.providers.oauth2.models import JWTAlgorithms, OAuth2Provider 28 29# See https://notes.salrahman.com/generate-es256-es384-es512-private-keys/ 30# and _CURVE_TYPES in the same file as the below curve files 31ec_crv_map = { 32 SECP256R1: "P-256", 33 SECP384R1: "P-384", 34 SECP521R1: "P-521", 35} 36min_length_map = { 37 SECP256R1: 32, 38 SECP384R1: 48, 39 SECP521R1: 66, 40} 41 42 43# https://github.com/jpadilla/pyjwt/issues/709 44def bytes_from_int(val: int, min_length: int = 0) -> bytes: 45 """Custom bytes_from_int that accepts a minimum length""" 46 remaining = val 47 byte_length = 0 48 49 while remaining != 0: 50 remaining >>= 8 51 byte_length += 1 52 length = max([byte_length, min_length]) 53 return val.to_bytes(length, "big", signed=False) 54 55 56def to_base64url_uint(val: int, min_length: int = 0) -> bytes: 57 """Custom to_base64url_uint that accepts a minimum length""" 58 if val < 0: 59 raise ValueError("Must be a positive integer") 60 61 int_bytes = bytes_from_int(val, min_length) 62 63 if len(int_bytes) == 0: 64 int_bytes = b"\x00" 65 66 return base64url_encode(int_bytes) 67 68 69def _jwks_from_public_key(public_key: PublicKeyTypes, cert: Certificate, kid: str, use: str): 70 """Convert given public key and certificate into JWKS data""" 71 key_data = {} 72 if isinstance(public_key, RSAPublicKey): 73 public_numbers = public_key.public_numbers() 74 key_data["kid"] = kid 75 key_data["kty"] = "RSA" 76 key_data["use"] = use 77 key_data["n"] = to_base64url_uint(public_numbers.n).decode() 78 key_data["e"] = to_base64url_uint(public_numbers.e).decode() 79 elif isinstance(public_key, EllipticCurvePublicKey): 80 public_numbers = public_key.public_numbers() 81 curve_type = type(public_key.curve) 82 key_data["kid"] = kid 83 key_data["kty"] = "EC" 84 key_data["use"] = use 85 key_data["x"] = to_base64url_uint(public_numbers.x, min_length_map[curve_type]).decode() 86 key_data["y"] = to_base64url_uint(public_numbers.y, min_length_map[curve_type]).decode() 87 key_data["crv"] = ec_crv_map.get(curve_type, public_key.curve.name) 88 elif isinstance(public_key, Ed25519PublicKey | Ed448PublicKey): 89 key_data["kid"] = kid 90 key_data["kty"] = "OKP" 91 key_data["use"] = use 92 key_data["crv"] = "Ed25519" if isinstance(public_key, Ed25519PublicKey) else "Ed448" 93 key_data["x"] = base64url_encode(public_key.public_bytes_raw()).decode() 94 elif isinstance(public_key, MLDSAKey): 95 # RFC 9964: ML-DSA keys use the AKP key type with the raw public key in `pub` 96 key_data["kid"] = kid 97 key_data["kty"] = "AKP" 98 key_data["use"] = use 99 key_data["pub"] = base64url_encode(public_key.public_bytes_raw()).decode() 100 else: 101 return key_data 102 key_data["x5c"] = [b64encode(cert.public_bytes(Encoding.DER)).decode("utf-8")] 103 key_data["x5t"] = ( 104 urlsafe_b64encode(cert.fingerprint(hashes.SHA1())).decode("utf-8").rstrip("=") # nosec 105 ) 106 key_data["x5t#S256"] = ( 107 urlsafe_b64encode(cert.fingerprint(hashes.SHA256())).decode("utf-8").rstrip("=") 108 ) 109 return key_data 110 111 112class JWKSView(View): 113 """Show RSA Key data for Provider""" 114 115 @staticmethod 116 def get_jwk_for_key(key: CertificateKeyPair, use: Literal["sig", "enc"]) -> dict | None: 117 """Convert a certificate-key pair into JWK""" 118 public_key = key.public_key 119 key_data = None 120 if not public_key: 121 return key_data 122 cert = key.certificate 123 124 key_data = _jwks_from_public_key(public_key, cert, key.kid, use) 125 126 if use == "sig": 127 key_data["alg"] = JWTAlgorithms.from_public_key(public_key) 128 elif use == "enc": 129 key_data["alg"] = "RSA-OAEP-256" 130 key_data["enc"] = "A256CBC-HS512" 131 132 return key_data 133 134 def get_keys(self) -> Generator[dict | None]: 135 provider_ids = Application.objects.filter( 136 slug=self.kwargs["application_slug"], 137 ).values_list( 138 "provider_id", 139 flat=True, 140 ) 141 provider = ( 142 OAuth2Provider.objects.select_related("signing_key", "encryption_key") 143 .filter(pk__in=provider_ids) 144 .first() 145 ) 146 147 if provider is None: 148 raise Http404() 149 150 if signing_key := provider.signing_key: 151 yield JWKSView.get_jwk_for_key(signing_key, "sig") 152 if encryption_key := provider.encryption_key: 153 yield JWKSView.get_jwk_for_key(encryption_key, "enc") 154 155 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 156 """Show JWK Key data for Provider""" 157 response_data = {} 158 for jwk in self.get_keys(): 159 if jwk: 160 response_data.setdefault("keys", []) 161 response_data["keys"].append(jwk) 162 163 response = JsonResponse(response_data) 164 response["Access-Control-Allow-Origin"] = "*" 165 166 return response
ec_crv_map =
{<class 'cryptography.hazmat.primitives.asymmetric.ec.SECP256R1'>: 'P-256', <class 'cryptography.hazmat.primitives.asymmetric.ec.SECP384R1'>: 'P-384', <class 'cryptography.hazmat.primitives.asymmetric.ec.SECP521R1'>: 'P-521'}
min_length_map =
{<class 'cryptography.hazmat.primitives.asymmetric.ec.SECP256R1'>: 32, <class 'cryptography.hazmat.primitives.asymmetric.ec.SECP384R1'>: 48, <class 'cryptography.hazmat.primitives.asymmetric.ec.SECP521R1'>: 66}
def
bytes_from_int(val: int, min_length: int = 0) -> bytes:
45def bytes_from_int(val: int, min_length: int = 0) -> bytes: 46 """Custom bytes_from_int that accepts a minimum length""" 47 remaining = val 48 byte_length = 0 49 50 while remaining != 0: 51 remaining >>= 8 52 byte_length += 1 53 length = max([byte_length, min_length]) 54 return val.to_bytes(length, "big", signed=False)
Custom bytes_from_int that accepts a minimum length
def
to_base64url_uint(val: int, min_length: int = 0) -> bytes:
57def to_base64url_uint(val: int, min_length: int = 0) -> bytes: 58 """Custom to_base64url_uint that accepts a minimum length""" 59 if val < 0: 60 raise ValueError("Must be a positive integer") 61 62 int_bytes = bytes_from_int(val, min_length) 63 64 if len(int_bytes) == 0: 65 int_bytes = b"\x00" 66 67 return base64url_encode(int_bytes)
Custom to_base64url_uint that accepts a minimum length
class
JWKSView(django.views.generic.base.View):
113class JWKSView(View): 114 """Show RSA Key data for Provider""" 115 116 @staticmethod 117 def get_jwk_for_key(key: CertificateKeyPair, use: Literal["sig", "enc"]) -> dict | None: 118 """Convert a certificate-key pair into JWK""" 119 public_key = key.public_key 120 key_data = None 121 if not public_key: 122 return key_data 123 cert = key.certificate 124 125 key_data = _jwks_from_public_key(public_key, cert, key.kid, use) 126 127 if use == "sig": 128 key_data["alg"] = JWTAlgorithms.from_public_key(public_key) 129 elif use == "enc": 130 key_data["alg"] = "RSA-OAEP-256" 131 key_data["enc"] = "A256CBC-HS512" 132 133 return key_data 134 135 def get_keys(self) -> Generator[dict | None]: 136 provider_ids = Application.objects.filter( 137 slug=self.kwargs["application_slug"], 138 ).values_list( 139 "provider_id", 140 flat=True, 141 ) 142 provider = ( 143 OAuth2Provider.objects.select_related("signing_key", "encryption_key") 144 .filter(pk__in=provider_ids) 145 .first() 146 ) 147 148 if provider is None: 149 raise Http404() 150 151 if signing_key := provider.signing_key: 152 yield JWKSView.get_jwk_for_key(signing_key, "sig") 153 if encryption_key := provider.encryption_key: 154 yield JWKSView.get_jwk_for_key(encryption_key, "enc") 155 156 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 157 """Show JWK Key data for Provider""" 158 response_data = {} 159 for jwk in self.get_keys(): 160 if jwk: 161 response_data.setdefault("keys", []) 162 response_data["keys"].append(jwk) 163 164 response = JsonResponse(response_data) 165 response["Access-Control-Allow-Origin"] = "*" 166 167 return response
Show RSA Key data for Provider
@staticmethod
def
get_jwk_for_key( key: authentik.crypto.models.CertificateKeyPair, use: Literal['sig', 'enc']) -> dict | None:
116 @staticmethod 117 def get_jwk_for_key(key: CertificateKeyPair, use: Literal["sig", "enc"]) -> dict | None: 118 """Convert a certificate-key pair into JWK""" 119 public_key = key.public_key 120 key_data = None 121 if not public_key: 122 return key_data 123 cert = key.certificate 124 125 key_data = _jwks_from_public_key(public_key, cert, key.kid, use) 126 127 if use == "sig": 128 key_data["alg"] = JWTAlgorithms.from_public_key(public_key) 129 elif use == "enc": 130 key_data["alg"] = "RSA-OAEP-256" 131 key_data["enc"] = "A256CBC-HS512" 132 133 return key_data
Convert a certificate-key pair into JWK
def
get_keys(self) -> Generator[dict | None]:
135 def get_keys(self) -> Generator[dict | None]: 136 provider_ids = Application.objects.filter( 137 slug=self.kwargs["application_slug"], 138 ).values_list( 139 "provider_id", 140 flat=True, 141 ) 142 provider = ( 143 OAuth2Provider.objects.select_related("signing_key", "encryption_key") 144 .filter(pk__in=provider_ids) 145 .first() 146 ) 147 148 if provider is None: 149 raise Http404() 150 151 if signing_key := provider.signing_key: 152 yield JWKSView.get_jwk_for_key(signing_key, "sig") 153 if encryption_key := provider.encryption_key: 154 yield JWKSView.get_jwk_for_key(encryption_key, "enc")
def
get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
156 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 157 """Show JWK Key data for Provider""" 158 response_data = {} 159 for jwk in self.get_keys(): 160 if jwk: 161 response_data.setdefault("keys", []) 162 response_data["keys"].append(jwk) 163 164 response = JsonResponse(response_data) 165 response["Access-Control-Allow-Origin"] = "*" 166 167 return response
Show JWK Key data for Provider