In an attempt to create a JWT in python I have written the following code.
#Headerheader = str({"alg": "RS256"})header_binary = header.encode()header_base64 = base64.urlsafe_b64encode(header_binary)print(header_base64)#Claims set (Pay Load)client_id="" username="" URL=""exp_time=str(round(time.time())+300) claims = str({"iss": client_id,"sub": username,"aud": URL,"exp": exp_time})claims_binary = claims.encode()claims_base64 = base64.urlsafe_b64encode(claims_binary)print(claims_base64)
I understand there is still more to do but I have the following problem. If I concatenate the two strings created above with a "." and put the resulting string in a JWT debugger it seems the claims set works perfectly but the same cannot be said for the header.
Please advise if this is the correct way to go about doing this and what my errors are.
Best Answer
Can you use third-party libraries? If so take a look at the docs.
Install the pyjwt
library using pip
:
pip install pyjwt
Example usage:
import jwt... # Define your payload variables# Encode JWTencoded_jwt = jwt.encode({"iss": client_id,"sub": username,"aud": URL,"exp": exp_time},'secret', algorithm='HS256')# Decode JWTdecoded_jwt = jwt.decode(encoded_jwt, 'secret', algorithms=['HS256'])
Python has a good module already created for this called, PyJWT. Try using that instead of following such a long process.
Also, it would allow you to use multiple algorithms to encode your data into, and other multiple features too.