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?
JOSE has a functionality that could be helpful for
.well-known/jwks.jsongeneration — ability to convert PEMs to dictionary compatible with JWK specification. However, produced dictionary utilizesbytes, instead ofstrin Python 3, which crashesjson.dumps.For example:
This will crash with
TypeError: Object of type bytes is not JSON serializabledue to all base64 encoded values being stored asbytesnotstr.The solution to circumvent the issue is:
However, is there a better way?