authentik.providers.oauth2.dpop

DPoP (Demonstrating Proof-of-Possession) utils

  1"""DPoP (Demonstrating Proof-of-Possession) utils"""
  2
  3import hashlib
  4import re
  5import time
  6from hmac import compare_digest
  7from urllib.parse import urlparse
  8
  9from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
 10from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes
 11from django.core.cache import cache
 12from django.db import transaction
 13from jwcrypto.jwk import JWK
 14from jwt import PyJWK
 15from jwt import decode as jwt_decode
 16from jwt import decode_complete as jwt_decode_complete
 17from jwt.exceptions import InvalidKeyError, InvalidTokenError, PyJWTError
 18from structlog.stdlib import get_logger
 19
 20from authentik.lib.jwt_mldsa import JWK_KTY_AKP, MLDSA_ALGORITHMS, key_from_jwk
 21
 22LOGGER = get_logger()
 23
 24
 25# DPoP JWT type header value
 26DPOP_JWT_TYPE = "dpop+jwt"
 27
 28# Supported asymmetric key types for DPoP. AKP (RFC 9964) carries ML-DSA keys.
 29DPOP_SUPPORTED_KTYS = {"EC", "RSA", JWK_KTY_AKP}
 30
 31DPOP_SUPPORTED_EC_CURVES = {"P-256", "P-384", "P-521"}
 32
 33# RSA key size limits for DPoP (bits)
 34DPOP_RSA_MIN_KEY_SIZE = 2048
 35DPOP_RSA_MAX_KEY_SIZE = 8192
 36
 37DPOP_JKT_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
 38
 39# Supported asymmetric signature algorithms for DPoP
 40DPOP_SUPPORTED_ALGS = {
 41    "ES256",
 42    "ES384",
 43    "ES512",
 44    "RS256",
 45    "RS384",
 46    "RS512",
 47    "PS256",
 48    "PS384",
 49    "PS512",
 50    # ML-DSA (RFC 9964), post-quantum
 51    *MLDSA_ALGORITHMS,
 52}
 53
 54# Required JWK members per RFC 7638, by key type. These are exactly the
 55# members the thumbprint is computed over, so a JWK rebuilt from only these
 56# has the same thumbprint and carries no additional user supplied extra
 57# claims (kid, alg, use, key_ops, x5c, x5u, jku, or unknown members).
 58JWK_REQUIRED_CLAIMS = {
 59    "EC": ("crv", "kty", "x", "y"),
 60    "RSA": ("e", "kty", "n"),
 61    # RFC 9964 Section 5: alg is REQUIRED on AKP keys and is part of the thumbprint
 62    JWK_KTY_AKP: ("alg", "kty", "pub"),
 63}
 64
 65# Clock skew tolerance in seconds for `iat` validation
 66DPOP_IAT_CLOCK_SKEW = 60
 67
 68# JTI replay protection window in seconds. Must cover the iat validity window
 69# (DPOP_IAT_CLOCK_SKEW) so a proof can never fall out of the replay cache
 70# while still being iat fresh. To avoid edge cases we use
 71# 3 * DPOP_IAT_CLOCK_SKEW rather than 2 * DPOP_IAT_CLOCK_SKEW.
 72DPOP_JTI_REPLAY_WINDOW = 3 * DPOP_IAT_CLOCK_SKEW
 73
 74# Cache key template for tracked JTIs
 75CACHE_KEY_DPOP_JTI = "authentik_providers_oauth2_dpop_jti_%s"
 76
 77
 78def jwk_thumbprint(jwk: dict) -> str:
 79    """Compute the SHA-256 JWK Thumbprint per RFC 7638"""
 80    return JWK(**jwk).thumbprint()
 81
 82
 83def is_valid_jkt(value: str) -> bool:
 84    """True if value is a well-formed base64url SHA-256 JWK thumbprint."""
 85    return bool(DPOP_JKT_RE.fullmatch(value))
 86
 87
 88def canonical_public_jwk(jwk: dict) -> dict:
 89    """Return a JWK containing only the RFC 7638 required public members."""
 90    kty = jwk.get("kty")
 91    members = JWK_REQUIRED_CLAIMS.get(kty)
 92    if members is None:
 93        raise DPoPError(f"Cannot canonicalize JWK of type {kty}")
 94    missing = [m for m in members if m not in jwk]
 95    if missing:
 96        raise DPoPError(f"JWK missing required members: {missing}")
 97    return {m: jwk[m] for m in members}
 98
 99
100class DPoPError(Exception):
101    """Raised when DPoP proof validation fails"""
102
103
104class DPoPValidator:
105    """Validates DPoP proof JWTs per RFC 9449 Section 5"""
106
107    def validate(
108        self,
109        dpop_proof: str,
110        expected_htm: str,
111        expected_htu: str,
112        expected_jkt: str | None = None,
113        expected_c_s256: str | None = None,
114    ) -> dict:
115        """Validate a DPoP proof JWT.
116
117        :param dpop_proof: The DPoP proof JWT string
118        :param expected_htm: Expected HTTP method (e.g., "POST")
119        :param expected_htu: Expected token endpoint URL
120        :param expected_jkt: Expected JWK thumbprint (from auth request)
121        :param expected_c_s256: Expected c_s256 hash (of code or device_code)
122        :return: The validated public key JWK dict
123        :raises DPoPError: If validation fails
124        """
125        header = self._extract_header(dpop_proof)
126        jwk, key = self._get_and_validate_jwk(header)
127        jwk = canonical_public_jwk(jwk)
128        alg = self._get_and_validate_alg(header)
129        payload = self._verify_signature(dpop_proof, jwk, alg, key)
130        jti = self._validate_payload_claims(payload, expected_htm, expected_htu)
131        self._check_jti_replay(jti)
132        self._validate_optional_claims(payload, expected_c_s256, expected_jkt, jwk)
133        return jwk
134
135    def _extract_header(self, dpop_proof: str) -> dict:
136        """Extract and return the unverified JOSE header."""
137        try:
138            unverified = jwt_decode_complete(
139                dpop_proof,
140                options={"verify_signature": False, "verify_exp": False, "verify_iat": False},
141            )
142            header = unverified.get("header", {})
143        except PyJWTError as exc:
144            raise DPoPError("Invalid DPoP proof JWT") from exc
145
146        if header.get("typ") != DPOP_JWT_TYPE:
147            raise DPoPError(f"Invalid DPoP typ header: {header.get('typ')}")
148        return header
149
150    def _get_and_validate_jwk(self, header: dict) -> tuple[dict, PublicKeyTypes | None]:
151        """Extract jwk from header and validate it.
152
153        Returns the raw jwk dict together with the public key already loaded
154        while validating an RSA or AKP key (or None for EC), so `_verify_signature`
155        can reuse it instead of re-parsing the same key material.
156        """
157        jwk = header.get("jwk")
158        if not isinstance(jwk, dict):
159            raise DPoPError("Missing jwk in DPoP header")
160        key = self._validate_jwk(jwk)
161        return jwk, key
162
163    def _get_and_validate_alg(self, header: dict) -> str:
164        """Extract and validate the alg header."""
165        alg = header.get("alg")
166        if not alg:
167            raise DPoPError("Missing alg in DPoP header")
168        if alg not in DPOP_SUPPORTED_ALGS:
169            raise DPoPError(f"Unsupported DPoP algorithm: {alg}")
170        jwk = header.get("jwk") or {}
171        if jwk.get("kty") == JWK_KTY_AKP and jwk.get("alg") != alg:
172            # An AKP key is bound to one algorithm; a proof naming another is malformed
173            raise DPoPError(f"DPoP alg {alg} does not match JWK alg {jwk.get('alg')}")
174        return alg
175
176    def _verify_signature(
177        self, dpop_proof: str, jwk: dict, alg: str, key: PublicKeyTypes | None = None
178    ) -> dict:
179        """Verify the DPoP proof signature and return the payload."""
180        try:
181            key = key or PyJWK.from_dict(jwk).key
182            return jwt_decode(dpop_proof, key, algorithms=[alg], options={"verify_iat": False})
183        except (PyJWTError, InvalidTokenError, TypeError, ValueError) as exc:
184            raise DPoPError("DPoP proof signature verification failed") from exc
185
186    def _validate_payload_claims(self, payload: dict, expected_htm: str, expected_htu: str) -> str:
187        """Validate htm, htu, iat, jti claims. Return the jti value."""
188        if payload.get("htm") != expected_htm:
189            raise DPoPError(f"DPoP htm mismatch: expected {expected_htm}, got {payload.get('htm')}")
190
191        payload_htu = payload.get("htu")
192        if not payload_htu:
193            raise DPoPError("DPoP proof missing htu claim")
194        if not self._htu_matches(payload_htu, expected_htu):
195            raise DPoPError(f"DPoP htu mismatch: expected {expected_htu}, got {payload_htu}")
196
197        iat = payload.get("iat")
198        if not isinstance(iat, int):
199            raise DPoPError("DPoP proof missing or invalid iat claim")
200        now = int(time.time())
201        if abs(now - iat) > DPOP_IAT_CLOCK_SKEW:
202            raise DPoPError("DPoP proof iat outside acceptable clock skew")
203
204        jti = payload.get("jti")
205        if not jti:
206            raise DPoPError("DPoP proof missing jti claim")
207
208        return jti
209
210    def _check_jti_replay(self, jti: str) -> None:
211        """Check if the jti has been seen before (replay protection)."""
212
213        # Only store the hash of the JTI to prevent memory-exhaustion attacks
214        # Recommended by RFC 9449 11.1
215        jti_hash = hashlib.sha256(jti.encode("utf-8")).hexdigest()
216        cache_key = CACHE_KEY_DPOP_JTI % jti_hash
217        # `cache.add()` is atomic set-if-not-exists. Wrap so when the cache
218        # backend is DB-backed (as in tests), a duplicate-key insert does not
219        # break the surrounding transaction.
220        with transaction.atomic():
221            added = cache.add(cache_key, True, timeout=DPOP_JTI_REPLAY_WINDOW)
222        if not added:
223            raise DPoPError("DPoP proof jti replay detected")
224
225    def _validate_optional_claims(
226        self,
227        payload: dict,
228        expected_c_s256: str | None,
229        expected_jkt: str | None,
230        jwk: dict,
231    ) -> None:
232        """Validate optional c_s256 and jkt claims if expected."""
233        if expected_c_s256 is not None:
234            proof_c_s256 = payload.get("c_s256")
235            if proof_c_s256 is None:
236                raise DPoPError("DPoP proof missing required c_s256 claim")
237            if not compare_digest(proof_c_s256, expected_c_s256):
238                raise DPoPError("DPoP proof c_s256 mismatch")
239
240        if expected_jkt is not None:
241            thumbprint = jwk_thumbprint(jwk)
242            if not compare_digest(thumbprint, expected_jkt):
243                raise DPoPError("DPoP proof JWK thumbprint mismatch")
244
245    def _validate_jwk(self, jwk: dict) -> PublicKeyTypes | None:
246        """Ensure the JWK is a public asymmetric key without private material.
247
248        Returns the public key loaded while checking an RSA key's size or an
249        AKP key's algorithm, so `_verify_signature` can reuse it instead of
250        re-parsing the same key.
251        """
252        kty = jwk.get("kty")
253        if kty not in DPOP_SUPPORTED_KTYS:
254            raise DPoPError(f"Unsupported JWK kty for DPoP: {kty}")
255
256        # Reject private material before loading anything. `priv` is the AKP private seed.
257        private_fields = {"d", "p", "q", "dp", "dq", "qi", "priv"}
258        if any(field in jwk for field in private_fields):
259            raise DPoPError("DPoP JWK must not contain private key material")
260
261        key = None
262        if kty == "RSA":
263            key = PyJWK.from_dict(jwk).key
264            if isinstance(key, RSAPublicKey) and key.key_size < DPOP_RSA_MIN_KEY_SIZE:
265                raise DPoPError("RSA key too small for DPoP (minimum 2048 bits)")
266            if isinstance(key, RSAPublicKey) and key.key_size > DPOP_RSA_MAX_KEY_SIZE:
267                raise DPoPError("RSA key too large for DPoP")
268        elif kty == "EC":
269            crv = jwk.get("crv")
270            if crv not in DPOP_SUPPORTED_EC_CURVES:
271                raise DPoPError(f"Unsupported EC curve for DPoP: {crv}")
272        elif kty == JWK_KTY_AKP:
273            if jwk.get("alg") not in MLDSA_ALGORITHMS:
274                raise DPoPError(f"Unsupported AKP algorithm for DPoP: {jwk.get('alg')}")
275            try:
276                key, _ = key_from_jwk(jwk)
277            except InvalidKeyError as exc:
278                # Malformed key, or ML-DSA unavailable in this OpenSSL configuration (FIPS)
279                raise DPoPError(f"Invalid AKP JWK: {exc}") from exc
280
281        return key
282
283    def _htu_matches(self, proof_htu: str, expected_htu: str) -> bool:
284        """Compare htu values ignoring query string and fragment"""
285        parsed_proof = urlparse(proof_htu)
286        parsed_expected = urlparse(expected_htu)
287        return (
288            parsed_proof.scheme == parsed_expected.scheme
289            and parsed_proof.netloc == parsed_expected.netloc
290            and parsed_proof.path == parsed_expected.path
291        )
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
DPOP_JWT_TYPE = 'dpop+jwt'
DPOP_SUPPORTED_KTYS = {'EC', 'RSA', 'AKP'}
DPOP_SUPPORTED_EC_CURVES = {'P-384', 'P-521', 'P-256'}
DPOP_RSA_MIN_KEY_SIZE = 2048
DPOP_RSA_MAX_KEY_SIZE = 8192
DPOP_JKT_RE = re.compile('^[A-Za-z0-9_-]{43}$')
DPOP_SUPPORTED_ALGS = {'ML-DSA-65', 'ES256', 'RS384', 'RS512', 'ES512', 'ES384', 'PS512', 'ML-DSA-87', 'PS384', 'PS256', 'ML-DSA-44', 'RS256'}
JWK_REQUIRED_CLAIMS = {'EC': ('crv', 'kty', 'x', 'y'), 'RSA': ('e', 'kty', 'n'), 'AKP': ('alg', 'kty', 'pub')}
DPOP_IAT_CLOCK_SKEW = 60
DPOP_JTI_REPLAY_WINDOW = 180
CACHE_KEY_DPOP_JTI = 'authentik_providers_oauth2_dpop_jti_%s'
def jwk_thumbprint(jwk: dict) -> str:
79def jwk_thumbprint(jwk: dict) -> str:
80    """Compute the SHA-256 JWK Thumbprint per RFC 7638"""
81    return JWK(**jwk).thumbprint()

Compute the SHA-256 JWK Thumbprint per RFC 7638

def is_valid_jkt(value: str) -> bool:
84def is_valid_jkt(value: str) -> bool:
85    """True if value is a well-formed base64url SHA-256 JWK thumbprint."""
86    return bool(DPOP_JKT_RE.fullmatch(value))

True if value is a well-formed base64url SHA-256 JWK thumbprint.

def canonical_public_jwk(jwk: dict) -> dict:
89def canonical_public_jwk(jwk: dict) -> dict:
90    """Return a JWK containing only the RFC 7638 required public members."""
91    kty = jwk.get("kty")
92    members = JWK_REQUIRED_CLAIMS.get(kty)
93    if members is None:
94        raise DPoPError(f"Cannot canonicalize JWK of type {kty}")
95    missing = [m for m in members if m not in jwk]
96    if missing:
97        raise DPoPError(f"JWK missing required members: {missing}")
98    return {m: jwk[m] for m in members}

Return a JWK containing only the RFC 7638 required public members.

class DPoPError(builtins.Exception):
101class DPoPError(Exception):
102    """Raised when DPoP proof validation fails"""

Raised when DPoP proof validation fails

class DPoPValidator:
105class DPoPValidator:
106    """Validates DPoP proof JWTs per RFC 9449 Section 5"""
107
108    def validate(
109        self,
110        dpop_proof: str,
111        expected_htm: str,
112        expected_htu: str,
113        expected_jkt: str | None = None,
114        expected_c_s256: str | None = None,
115    ) -> dict:
116        """Validate a DPoP proof JWT.
117
118        :param dpop_proof: The DPoP proof JWT string
119        :param expected_htm: Expected HTTP method (e.g., "POST")
120        :param expected_htu: Expected token endpoint URL
121        :param expected_jkt: Expected JWK thumbprint (from auth request)
122        :param expected_c_s256: Expected c_s256 hash (of code or device_code)
123        :return: The validated public key JWK dict
124        :raises DPoPError: If validation fails
125        """
126        header = self._extract_header(dpop_proof)
127        jwk, key = self._get_and_validate_jwk(header)
128        jwk = canonical_public_jwk(jwk)
129        alg = self._get_and_validate_alg(header)
130        payload = self._verify_signature(dpop_proof, jwk, alg, key)
131        jti = self._validate_payload_claims(payload, expected_htm, expected_htu)
132        self._check_jti_replay(jti)
133        self._validate_optional_claims(payload, expected_c_s256, expected_jkt, jwk)
134        return jwk
135
136    def _extract_header(self, dpop_proof: str) -> dict:
137        """Extract and return the unverified JOSE header."""
138        try:
139            unverified = jwt_decode_complete(
140                dpop_proof,
141                options={"verify_signature": False, "verify_exp": False, "verify_iat": False},
142            )
143            header = unverified.get("header", {})
144        except PyJWTError as exc:
145            raise DPoPError("Invalid DPoP proof JWT") from exc
146
147        if header.get("typ") != DPOP_JWT_TYPE:
148            raise DPoPError(f"Invalid DPoP typ header: {header.get('typ')}")
149        return header
150
151    def _get_and_validate_jwk(self, header: dict) -> tuple[dict, PublicKeyTypes | None]:
152        """Extract jwk from header and validate it.
153
154        Returns the raw jwk dict together with the public key already loaded
155        while validating an RSA or AKP key (or None for EC), so `_verify_signature`
156        can reuse it instead of re-parsing the same key material.
157        """
158        jwk = header.get("jwk")
159        if not isinstance(jwk, dict):
160            raise DPoPError("Missing jwk in DPoP header")
161        key = self._validate_jwk(jwk)
162        return jwk, key
163
164    def _get_and_validate_alg(self, header: dict) -> str:
165        """Extract and validate the alg header."""
166        alg = header.get("alg")
167        if not alg:
168            raise DPoPError("Missing alg in DPoP header")
169        if alg not in DPOP_SUPPORTED_ALGS:
170            raise DPoPError(f"Unsupported DPoP algorithm: {alg}")
171        jwk = header.get("jwk") or {}
172        if jwk.get("kty") == JWK_KTY_AKP and jwk.get("alg") != alg:
173            # An AKP key is bound to one algorithm; a proof naming another is malformed
174            raise DPoPError(f"DPoP alg {alg} does not match JWK alg {jwk.get('alg')}")
175        return alg
176
177    def _verify_signature(
178        self, dpop_proof: str, jwk: dict, alg: str, key: PublicKeyTypes | None = None
179    ) -> dict:
180        """Verify the DPoP proof signature and return the payload."""
181        try:
182            key = key or PyJWK.from_dict(jwk).key
183            return jwt_decode(dpop_proof, key, algorithms=[alg], options={"verify_iat": False})
184        except (PyJWTError, InvalidTokenError, TypeError, ValueError) as exc:
185            raise DPoPError("DPoP proof signature verification failed") from exc
186
187    def _validate_payload_claims(self, payload: dict, expected_htm: str, expected_htu: str) -> str:
188        """Validate htm, htu, iat, jti claims. Return the jti value."""
189        if payload.get("htm") != expected_htm:
190            raise DPoPError(f"DPoP htm mismatch: expected {expected_htm}, got {payload.get('htm')}")
191
192        payload_htu = payload.get("htu")
193        if not payload_htu:
194            raise DPoPError("DPoP proof missing htu claim")
195        if not self._htu_matches(payload_htu, expected_htu):
196            raise DPoPError(f"DPoP htu mismatch: expected {expected_htu}, got {payload_htu}")
197
198        iat = payload.get("iat")
199        if not isinstance(iat, int):
200            raise DPoPError("DPoP proof missing or invalid iat claim")
201        now = int(time.time())
202        if abs(now - iat) > DPOP_IAT_CLOCK_SKEW:
203            raise DPoPError("DPoP proof iat outside acceptable clock skew")
204
205        jti = payload.get("jti")
206        if not jti:
207            raise DPoPError("DPoP proof missing jti claim")
208
209        return jti
210
211    def _check_jti_replay(self, jti: str) -> None:
212        """Check if the jti has been seen before (replay protection)."""
213
214        # Only store the hash of the JTI to prevent memory-exhaustion attacks
215        # Recommended by RFC 9449 11.1
216        jti_hash = hashlib.sha256(jti.encode("utf-8")).hexdigest()
217        cache_key = CACHE_KEY_DPOP_JTI % jti_hash
218        # `cache.add()` is atomic set-if-not-exists. Wrap so when the cache
219        # backend is DB-backed (as in tests), a duplicate-key insert does not
220        # break the surrounding transaction.
221        with transaction.atomic():
222            added = cache.add(cache_key, True, timeout=DPOP_JTI_REPLAY_WINDOW)
223        if not added:
224            raise DPoPError("DPoP proof jti replay detected")
225
226    def _validate_optional_claims(
227        self,
228        payload: dict,
229        expected_c_s256: str | None,
230        expected_jkt: str | None,
231        jwk: dict,
232    ) -> None:
233        """Validate optional c_s256 and jkt claims if expected."""
234        if expected_c_s256 is not None:
235            proof_c_s256 = payload.get("c_s256")
236            if proof_c_s256 is None:
237                raise DPoPError("DPoP proof missing required c_s256 claim")
238            if not compare_digest(proof_c_s256, expected_c_s256):
239                raise DPoPError("DPoP proof c_s256 mismatch")
240
241        if expected_jkt is not None:
242            thumbprint = jwk_thumbprint(jwk)
243            if not compare_digest(thumbprint, expected_jkt):
244                raise DPoPError("DPoP proof JWK thumbprint mismatch")
245
246    def _validate_jwk(self, jwk: dict) -> PublicKeyTypes | None:
247        """Ensure the JWK is a public asymmetric key without private material.
248
249        Returns the public key loaded while checking an RSA key's size or an
250        AKP key's algorithm, so `_verify_signature` can reuse it instead of
251        re-parsing the same key.
252        """
253        kty = jwk.get("kty")
254        if kty not in DPOP_SUPPORTED_KTYS:
255            raise DPoPError(f"Unsupported JWK kty for DPoP: {kty}")
256
257        # Reject private material before loading anything. `priv` is the AKP private seed.
258        private_fields = {"d", "p", "q", "dp", "dq", "qi", "priv"}
259        if any(field in jwk for field in private_fields):
260            raise DPoPError("DPoP JWK must not contain private key material")
261
262        key = None
263        if kty == "RSA":
264            key = PyJWK.from_dict(jwk).key
265            if isinstance(key, RSAPublicKey) and key.key_size < DPOP_RSA_MIN_KEY_SIZE:
266                raise DPoPError("RSA key too small for DPoP (minimum 2048 bits)")
267            if isinstance(key, RSAPublicKey) and key.key_size > DPOP_RSA_MAX_KEY_SIZE:
268                raise DPoPError("RSA key too large for DPoP")
269        elif kty == "EC":
270            crv = jwk.get("crv")
271            if crv not in DPOP_SUPPORTED_EC_CURVES:
272                raise DPoPError(f"Unsupported EC curve for DPoP: {crv}")
273        elif kty == JWK_KTY_AKP:
274            if jwk.get("alg") not in MLDSA_ALGORITHMS:
275                raise DPoPError(f"Unsupported AKP algorithm for DPoP: {jwk.get('alg')}")
276            try:
277                key, _ = key_from_jwk(jwk)
278            except InvalidKeyError as exc:
279                # Malformed key, or ML-DSA unavailable in this OpenSSL configuration (FIPS)
280                raise DPoPError(f"Invalid AKP JWK: {exc}") from exc
281
282        return key
283
284    def _htu_matches(self, proof_htu: str, expected_htu: str) -> bool:
285        """Compare htu values ignoring query string and fragment"""
286        parsed_proof = urlparse(proof_htu)
287        parsed_expected = urlparse(expected_htu)
288        return (
289            parsed_proof.scheme == parsed_expected.scheme
290            and parsed_proof.netloc == parsed_expected.netloc
291            and parsed_proof.path == parsed_expected.path
292        )

Validates DPoP proof JWTs per RFC 9449 Section 5

def validate( self, dpop_proof: str, expected_htm: str, expected_htu: str, expected_jkt: str | None = None, expected_c_s256: str | None = None) -> dict:
108    def validate(
109        self,
110        dpop_proof: str,
111        expected_htm: str,
112        expected_htu: str,
113        expected_jkt: str | None = None,
114        expected_c_s256: str | None = None,
115    ) -> dict:
116        """Validate a DPoP proof JWT.
117
118        :param dpop_proof: The DPoP proof JWT string
119        :param expected_htm: Expected HTTP method (e.g., "POST")
120        :param expected_htu: Expected token endpoint URL
121        :param expected_jkt: Expected JWK thumbprint (from auth request)
122        :param expected_c_s256: Expected c_s256 hash (of code or device_code)
123        :return: The validated public key JWK dict
124        :raises DPoPError: If validation fails
125        """
126        header = self._extract_header(dpop_proof)
127        jwk, key = self._get_and_validate_jwk(header)
128        jwk = canonical_public_jwk(jwk)
129        alg = self._get_and_validate_alg(header)
130        payload = self._verify_signature(dpop_proof, jwk, alg, key)
131        jti = self._validate_payload_claims(payload, expected_htm, expected_htu)
132        self._check_jti_replay(jti)
133        self._validate_optional_claims(payload, expected_c_s256, expected_jkt, jwk)
134        return jwk

Validate a DPoP proof JWT.

:param dpop_proof: The DPoP proof JWT string :param expected_htm: Expected HTTP method (e.g., "POST") :param expected_htu: Expected token endpoint URL :param expected_jkt: Expected JWK thumbprint (from auth request) :param expected_c_s256: Expected c_s256 hash (of code or device_code) :return: The validated public key JWK dict :raises DPoPError: If validation fails