Skip to content

Add PyJWK.to_dict and PyJWKSet.to_dict #1106

@dmytro-GL

Description

@dmytro-GL

It would be nice to have to_dict methods in PyJWK and PyJWKSet for consistency with from_dict.

For JWK, right now there seem to be two ways to obtain the original data:

  1. via protected _jwk_data
>>> jwk = jwt.PyJWK.from_dict(jwk_data)
>>> jwk._jwk_data
{'kty': 'EC', 'use': 'sig', 'key_ops': ['sign'], 'alg': 'ES256', 'kid': '9174af71-46fe-4c1a-ab1e-f055905c39e6', 'crv': 'P-256', 'x': 'ZMqZAhTNoV2vmMKqfGjbzXc1Jl2QjGe0F5p3crQeuiA', 'y': '9WWXO0euo8J2UT8bs4MXjhEMdunCrenuBJIUxxwCeek', 'd': '2KaMrkdaUS11BAdSIELKUC_sm5CYOnVNjgXwBxeJrhw'}
  1. via Algorithm.to_jwk (but in this case, kid, use, etc. are not preserved)
>>> jwk = jwt.PyJWK.from_dict(jwk_data)
>>> jwk.Algorithm.to_jwk(jwk.key, as_dict=True)
{'kty': 'EC', 'crv': 'P-256', 'x': 'ZMqZAhTNoV2vmMKqfGjbzXc1Jl2QjGe0F5p3crQeuiA', 'y': '9WWXO0euo8J2UT8bs4MXjhEMdunCrenuBJIUxxwCeek', 'd': '2KaMrkdaUS11BAdSIELKUC_sm5CYOnVNjgXwBxeJrhw'}

For JWKS, you have to convert each key in keys to dict manually.

It also would be nice to be able to convert a private JWK to a public JWK.
The second approach works, but again, kid is not preserved:

>>> jwk.Algorithm.to_jwk(jwk.key.public_key(), as_dict=True)
{'kty': 'EC', 'crv': 'P-256', 'x': 'ZMqZAhTNoV2vmMKqfGjbzXc1Jl2QjGe0F5p3crQeuiA', 'y': '9WWXO0euo8J2UT8bs4MXjhEMdunCrenuBJIUxxwCeek'}

python-jose has to_dict, though it also doesn't preserve kid.

>>> k
<jose.backends.cryptography_backend.CryptographyECKey object at 0x7f0a8f6dcb60>
>>> k.to_dict()
{'alg': 'ES256', 'kty': 'EC', 'crv': 'P-256', 'x': 'ZMqZAhTNoV2vmMKqfGjbzXc1Jl2QjGe0F5p3crQeuiA', 'y': '9WWXO0euo8J2UT8bs4MXjhEMdunCrenuBJIUxxwCeek', 'd': '2KaMrkdaUS11BAdSIELKUC_sm5CYOnVNjgXwBxeJrhw'}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions