123456789101112131415161718192021222324252627282930313233 |
- import time
- import jwt
- JWT_TOKEN_EXPIRE_SECONDS = 3600 * 24 * 7 # token有效时间 7天
- JWT_TOKEN_SECRET_SALT = 'jasonphd.2024.ttb'
- JWT_TOKEN_ALGORITHM = 'HS256' # HASH算法
- def generate_jwt_token(user: str) -> str:
- """根据用户id生成token"""
- data = {'user_id': user, 'exp': int(time.time()) + JWT_TOKEN_EXPIRE_SECONDS}
- print("generate data:", data)
- jwtToken = jwt.encode(data, JWT_TOKEN_SECRET_SALT, algorithm=JWT_TOKEN_ALGORITHM)
- return jwtToken
- def verify_jwt_token(user: str, jwtToken: str) -> bool:
- """验证用户token"""
- data = {'user_id': user}
- try:
- payload = jwt.decode(jwtToken, JWT_TOKEN_SECRET_SALT, algorithms=[JWT_TOKEN_ALGORITHM])
- print("verify:", payload)
- exp = int(payload.pop('exp'))
- if time.time() > exp:
- print('已失效')
- return False
- return data == payload
- except jwt.exceptions.ExpiredSignatureError as ex:
- print('token签名过期:', ex)
- except jwt.PyJWTError as ex:
- print('token解析失败:', ex)
- return False
|