Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a JWT in Python?

Tags:

python

jwt

In an attempt to create a JWT in Python I have written the following code.

# Header
header = str({"alg": "RS256"})
header_binary = header.encode()
header_base64 = base64.urlsafe_b64encode(header_binary)
print(header_base64)

# Claims set (Payload)
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.

like image 536
Brian de Klerk Avatar asked Nov 06 '25 11:11

Brian de Klerk


2 Answers

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 JWT
encoded_jwt = jwt.encode({"iss": client_id,
      "sub": username,
      "aud": URL,
      "exp": exp_time},
      'secret', algorithm='HS256')

# Decode JWT
decoded_jwt = jwt.decode(encoded_jwt, 'secret', algorithms=['HS256'])
like image 104
Diogo Silva Avatar answered Nov 09 '25 09:11

Diogo Silva


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.

like image 25
Trishant Pahwa Avatar answered Nov 09 '25 07:11

Trishant Pahwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!