Feature: add to_dict() and to_json() to PyJWK and PyJWKSet#1184
Open
pranavkumaarofficial wants to merge 1 commit into
Open
Feature: add to_dict() and to_json() to PyJWK and PyJWKSet#1184pranavkumaarofficial wants to merge 1 commit into
pranavkumaarofficial wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PyJWKandPyJWKSetcan be constructed from dictionaries viafrom_dict(),but there is no public way to serialize them back. The only workaround is
accessing the private
_jwk_dataattribute or usingAlgorithm.to_jwk(),which loses metadata like
kid,use, andalg.This adds
to_dict()andto_json()methods to both classes, enablinglossless round-tripping of JWK objects while preserving all metadata fields.
Changes
jwt/api_jwk.py: Addedto_dict()andto_json()toPyJWKandPyJWKSettests/test_api_jwk.py: Added 10 tests covering round-trips for RSA (public + private), EC, HMAC, OKP key types, metadata preservation, JSON serialization, keyset round-trips, and unusable key filteringCHANGELOG.rst: Added entry under[Unreleased] > AddedDesign notes
PyJWK.to_dict()returns a shallow copy of the internal_jwk_datadictionary that was passed in during construction. This is intentional:
it preserves all original JWK fields (including
kid,use,alg,key_ops) thatAlgorithm.to_jwk()would drop.PyJWKSet.to_dict()returns{"keys": [...]}containing only the keysthat were successfully parsed during construction. Keys with unsupported
algorithms that were skipped on input will not appear in the output.
How to test
pytest tests/test_api_jwk.py -v -k "to_dict or to_json"
Closes #1106