Thanks to visit codestin.com
Credit goes to github.com

Skip to content

JWK can not be dumped to JSON #127

@galak-fyyar

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:

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions