Jay Patel
Jay Patel

Reputation: 2451

How to generate JWT in python according to the requirement

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

Answers (2)

DatGeoudon
DatGeoudon

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

Jonas
Jonas

Reputation: 402

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

Upvotes: 13

Related Questions