Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWK can not be dumped to JSON #127

Closed
galak-fyyar opened this issue Mar 13, 2019 · 0 comments · Fixed by #165
Closed

JWK can not be dumped to JSON #127

galak-fyyar opened this issue Mar 13, 2019 · 0 comments · Fixed by #165
Labels

Comments

@galak-fyyar
Copy link

galak-fyyar commented Mar 13, 2019

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:

import json
from jose import jwk


key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEU7X2p6GjDeHWgvDkWZHcjKLXdNwM
ua9kolwyy3nv7k3xiRgX/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:

import json
from jose import jwk


class ByteEncoder(json.JSONEncoder):
    #pylint: disable=method-hidden
    def default(self, x):
        if isinstance(x, bytes):
            return str(x, "UTF-8")
        else:
            super().default(x)


key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEU7X2p6GjDeHWgvDkWZHcjKLXdNwM
ua9kolwyy3nv7k3xiRgX/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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants