Skip to content

JWK can not be dumped to JSON #127

Description

@galak-fyyar

JOSE has a functionality that could be helpful for .well-known/jwks.json generation — ability to convert PEMs to dictionary compatible with JWK specification. However, produced dictionary utilizes bytes, instead of str in Python 3, which crashes json.dumps.

For example:

importjsonfromjoseimportjwkkey_pem="""-----BEGIN PUBLIC KEY-----MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEU7X2p6GjDeHWgvDkWZHcjKLXdNwMua9kolwyy3nv7k3xiRgX/jfX1QbXaQuvqr40PhoWjtJR2C9uTvyP6AMHkw==-----END PUBLIC KEY-----"""key=jwk.construct(key_pem, algorithm="ES256").to_dict()
json.dumps({"keys": [key]})

This will crash with TypeError: Object of type bytes is not JSON serializable due to all base64 encoded values being stored as bytes not str.

The solution to circumvent the issue is:

importjsonfromjoseimportjwkclassByteEncoder(json.JSONEncoder):
#pylint: disable=method-hiddendefdefault(self, x):
ifisinstance(x, bytes):
returnstr(x, "UTF-8")
else:
super().default(x)
key_pem="""-----BEGIN PUBLIC KEY-----MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEU7X2p6GjDeHWgvDkWZHcjKLXdNwMua9kolwyy3nv7k3xiRgX/jfX1QbXaQuvqr40PhoWjtJR2C9uTvyP6AMHkw==-----END PUBLIC KEY-----"""key=jwk.construct(key_pem, algorithm="ES256").to_dict()
json.dumps({"keys": [key]}, cls=ByteEncoder)

However, is there a better way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions