Skip to content

Feature: add to_dict() and to_json() to PyJWK and PyJWKSet#1184

Open
pranavkumaarofficial wants to merge 1 commit into
jpadilla:masterfrom
pranavkumaarofficial:feature/pyjwk-to-dict
Open

Feature: add to_dict() and to_json() to PyJWK and PyJWKSet#1184
pranavkumaarofficial wants to merge 1 commit into
jpadilla:masterfrom
pranavkumaarofficial:feature/pyjwk-to-dict

Conversation

@pranavkumaarofficial

Copy link
Copy Markdown

Summary

PyJWK and PyJWKSet can be constructed from dictionaries via from_dict(),
but there is no public way to serialize them back. The only workaround is
accessing the private _jwk_data attribute or using Algorithm.to_jwk(),
which loses metadata like kid, use, and alg.

This adds to_dict() and to_json() methods to both classes, enabling
lossless round-tripping of JWK objects while preserving all metadata fields.

Changes

  • jwt/api_jwk.py: Added to_dict() and to_json() to PyJWK and PyJWKSet
  • tests/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 filtering
  • CHANGELOG.rst: Added entry under [Unreleased] > Added

Design notes

PyJWK.to_dict() returns a shallow copy of the internal _jwk_data
dictionary that was passed in during construction. This is intentional:
it preserves all original JWK fields (including kid, use, alg,
key_ops) that Algorithm.to_jwk() would drop.

PyJWKSet.to_dict() returns {"keys": [...]} containing only the keys
that 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add PyJWK.to_dict and PyJWKSet.to_dict

1 participant