jpadilla / pyjwt

JSON Web Token implementation in Python
https://pyjwt.readthedocs.io
MIT License
5.08k stars 679 forks source link

Add `Algorithm.compute_hash_digest` and use it to implement at_hash validation example #775

Closed sirosen closed 1 year ago

sirosen commented 2 years ago

Algorithm.compute_hash_digest is defined as a method which inspects the object to see that it has the requisite attributes, hash_alg.

If hash_alg is not set, then the method raises a NotImplementedError. This applies to classes like NoneAlgorithm.

If hash_alg is set, then it is checked for

has_crypto  # is cryptography available?
and isinstance(hash_alg, type)
and issubclass(hash_alg, hashes.HashAlgorithm)

to see which API for computing a digest is appropriate -- hashlib vs cryptography.hazmat.primitives.hashes.

These checks could be avoided at runtime if it were necessary to optimize further (e.g. attach compute_hash_digest methods to classeswith a class decorator) but this is not clearly a worthwhile optimization. Such perf tuning is intentionally omitted for now.


Add doc example of OIDC login flow to demonstrate get_algorithm_by_name and compute_hash_digest. The end goal is an example with at_hash validation. It is not meant to be a "guaranteed correct" and spec-compliant example, so the doc notes simply that additional reading about OIDC is recommended.

closes #314


If the example usage is too bulky and complicated, I'm happy to pull that and only focus on the new method on Algorithm, or to pull that out into a separate PR. It seemed more efficient to just put both changes together.