SoFunction
Updated on 2024-11-18

Problems with wrapping tokens in python

python wrapped token

import datetime


class MyJwt:
    
    def __init__(self):
        # Encryption key
         = "1231231241234refd"
    
    # Encryption methods
    def encode_jwt(self,userinfo):

        # Encryption operations
        encode_srt = (userinfo,,algorithm="HS256")

        try:
            encode_srt = str(encode_srt,"utf-8")
        except Exception as e:
            pass
        return encode_srt


    # Encrypted from time to time
    # userinfo :userinfo
    # mytime: set expiration time
    def encode_jwt_t(self,userinfo,mytime):
        playload = {
            'exp': int((()+(seconds=mytime)).timestamp()),
            'data':userinfo
        }
        # Encryption operations
        encode_srt = (playload,, algorithm="HS256")

        try:
            encode_srt = str(encode_srt, "utf-8")
        except Exception as e:
            pass
        return encode_srt

    # Decryption
    def decode_jwt(self,jwt_str):
        return (jwt_str,,algorithms=['HS256'])

How to encapsulate the token and call it directly

import jwt
import time
 
 
class JwtTool:
    # Generate token
    def create_token(self, payload, ex):
        a = "sss"
        payload['ex'] = int(()) + ex
        try:
            token = (payload, key=a)
            print("Generated token successfully", token)
            return token
        except Exception as e:
            print("Error generating token.", e)
            return False
    #Parsing the token
    def check_token(self, token):
        try:
            a = "sss"
            payload = (token, key=a, algorithms="HS256")
            print("Parsing token successful.", payload)
            return payload
        except Exception as e:
            print("Error parsing token.", e)
            return False
 
 
# Separate file test
if __name__ == '__main__':
    from app import app
 
    with app.app_context():
        j = JwtTool()
        payload = {
            "ia": 1,
            "name": "Millet."
        }
        token = j.create_token(payload, 200)
        print("-----", token)
        # token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYSI6MSwibmFtZSI6Ilx1NWMwZlx1N2M3MyJ9.ru9-3H7Z9abbkKXkZMbekeAEdlE-COw9CASYMxIG728"
        # print("++++",j.check_token(token))

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.