Reputation: 2451
I'm trying to generate JWT to use it in a API integration. Here are the specific requirements to generate JWT token but I'm not following how to do it in python.
It shows following Java snippet:
JWT.create()
.withIssuer("CLIENT_ID")
.withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5)))
.sign(Algorithm.HMAC256("CLIENT_SECRET"));
And accordingly, I'm trying to create it... Here I'm using JWT lib in python and here is my code:
from datetime import datetime, timedelta, timezone
from jwt import JWT
from jwt.utils import get_int_from_datetime
instance = JWT()
message = {
'iss': 'CLIENT_ID',
'exp': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(hours=23))
}
signing_key = 'CLIENT_SECRET'
compact_jws = instance.encode(message, signing_key, alg='HS256')
print('compact_jws', compact_jws)
But the above code gives me the following error:
TypeError: key must be an instance of a class implements jwt.AbstractJWKBase
I'm not sure whether the code I've written is correct according to the requirements or not, please help me.
Upvotes: 13
Views: 30498
Reputation: 434
If you are stuck with python-jwt
, you want to use supported_key_types
:
from jwt import JWT, supported_key_types
secret = b'...'
payload = ...
# Create a key from our secret
key = supported_key_types()['oct'](secret)
# To encode
my_token = JWT().encode(payload, key, alg='HS256')
# To decode
payload_dec = JWT().decode(my_token, key)
Upvotes: 0