I was looking to sign and verify my JWT token using JWK public and private keys. To generate JWK public and private keys, I will have to use the authlib.jose (Authlib) lib as it is already present in our product and I do not want to use a new lib say jwcrypto.
To do this, I tried using the generate_key from ECKey class but that will only give me either a public key or a private key and not both.
wanted to know if there is some lib within authlib to do this.
There is a solution by having our own version of generate_keys, but is there one already existing in authlib lib ?
from authlib.jose import jwt as authlib_jwt, JsonWebToken
class JwkPair(ECKey):
@classmethod
def generate_key(cls, crv='P-256', options=None) -> 'ECKey':
if crv not in cls.DSS_CURVES:
raise ValueError(f'Invalid crv value: "{crv}"')
raw_key_private = ec.generate_private_key(
curve=cls.DSS_CURVES[crv](),
backend=default_backend(),
)
raw_public_key = raw_key_private.public_key()
return cls(private_key=raw_key_private, public_key=raw_public_key, options=options)
jwk = JwkPair.generate_key(crv='P-384', options=options)
jwk_public_key = jwk.dumps_public_key()
jwk_private_key = jwk.dumps_private_key()
data = {"name": "nagarjun"}
encoded_jwt = authlib_jwt.encode(header=header, payload=data, key=jwk_private_key)
jwt_algo = JsonWebToken("ES384")
claims_algo = jwt_algo.decode(encoded_jwt, jwk_public_key)
claims_algo.validate()