How to generate JWT in python according to the requirement

Viewed 7735

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.

1 Answers

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
Related