简体   繁体   中英

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 (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.

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.

Can you use third-party libraries? If so take a look at the docs

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM