Brian de Klerk
Brian de Klerk

Reputation: 49

How to encode a JWT in Python?

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.

Upvotes: 3

Views: 19735

Answers (2)

Diogo Silva
Diogo Silva

Reputation: 330

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'])

Upvotes: 3

Trishant Pahwa
Trishant Pahwa

Reputation: 2943

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.

Upvotes: 1

Related Questions