一、安裝包
pip install pyjwt
二、代碼邏輯實現
import time import jwt class Token(object): def __init__(self): pass @classmethod def encrpyt_token(cls,username,uuid,exptime=None,secret=None): """ iss:該JWT的簽發者,是否使用是可以選擇的。 sub:該JWT所面向的用戶,是否使用是可選的。 aud:接收該JWT的一方,是否使用是可選的。 exp(expires):什么時候過期,是一個UNIX的時間戳,是否使用是可選的。默認設置為:30分鍾 iat(issued at):在什么時候簽發UNIX時間,是否使用是可選的。 nbf(not before):如果當前時間在nbf的時間之前,則Token不被接受,一般都會留幾分鍾,是否使用是可選的。 :return: """ if not exptime: exptime = time.time() + 60*30 if not secret: secret = 'iam' payloads = { 'iss': 'IAM JWT Builder', 'iat': time.time(), 'username':username, 'uuid':str(uuid), "exp": exptime } encoded_jwt = jwt.encode(payloads, secret, algorithm='HS256') return encoded_jwt @classmethod def decrypt_token(cls,token,secret=None): """ encoded_jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJJQU0gSldUIEJ1aWxkZXIiLCJpYXQiOjE1ODQzNDA0NjkuOTE5ODQxLCJ1c2VybmFtZSI6Inl1bGlhbmh1aTEiLCJ1dWlkIjoiOTQwYjBhZTgtNWEwNi0xMWVhLWEzNWItZjEwNWMyOGI2NDE2IiwiZXhwIjoxNTg0MzQyMjY5LjkxOTg0MX0.zITnwaB0zsuyO1kiyYBG5IFWEy5FewDGSJAj1eJ-uEg' decode_jwt = jwt.decode(encoded_jwt, 'iam', algorithms=['HS256']) print('decode_jwt',decode_jwt) :param token: :param secret: :return: """ try: if not secret: secret = 'iam' decode_jwt = jwt.decode(token, secret, algorithms=['HS256']) return decode_jwt except jwt.exceptions.InvalidSignatureError as e: return {'error':'Signature verification failed'} authToken = Token()