How to generate JWT in python according to the requirement
Asked Answered
R

2

12

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.

Ralph answered 2/6, 2020 at 11:14 Comment(2)
Your signing_key is just a plain string. And it should be instance [of subtype] of jwt.AbstractJWKBaseHowdy
Yeah, I understood it from the error message, but how to solve that issue?Ralph
C
13

Try to use pyjwt: PyJWT instead of jwt

Then you can do the following:

encoded_jwt = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')

install it with:

pip install pyjwt

and use it as:

import jwt
Castle answered 20/7, 2020 at 7:43 Comment(0)
E
0

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)
Ent answered 26/7 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.