python-jwt的生成和解析

JWT的生成和解析.


需要安装的jwt 是PyJWT.否则可能会有别的问题出现.

# jwt卸载命令
pip uninstall jwt
# 保险起见,将PyJWT一同卸载
pip uninstall PyJWT
# 重新安装PyJWT
pip install PyJWT==1.7.1

代码

import datetime

import jwt

salt = 'iv%x1fo9l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='


def generate_token(play_load: dict, minutes: int):
    """
    生成token
    :param minutes: 多久过期,单位:分钟
    :param play_load: 一般为用户id、用户名的字典
    :return:
    """
    # 构造header
    headers = {
        'type': 'jwt',
        'alg': 'HS256'
    }
    # token有效期,我这边设置为了分钟,即x分钟后过期
    play_load['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=minutes)
    # 构造signature即token
    token = jwt.encode(payload=play_load, key=salt, algorithm="HS256", headers=headers).decode()
    return token


def validate_token(token):
    """
    校验token有效性
    :param token:加密token
    :return: 状态
    """

    # 定义返回相应字典
    result = {'status': False, 'data': None, 'error': None}
    try:
        verified_payload = jwt.decode(token, salt, algorithm='HS256', options={"verify_signature": False})
        result['status'] = True
        result['data'] = verified_payload
    except jwt.ExpiredSignatureError:
        result['error'] = 'token已失效'
    except jwt.DecodeError as err:
        result['error'] = 'token认证失败'
    except jwt.InvalidTokenError:
        result['error'] = '非法的token'
    return result



if __name__ == '__main__':
    print(generate_token({"code": 1},1))
    print(validate_token('eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJjb2RlIjoxLCJleHAiOjE2Mzk2NDIxODl9.U7AuG6GKVC1j_eInrsNmC-z1Xi_RyMOkuWWTS-01VeI'))

你可能感兴趣的:(python,python,开发语言,后端)