TokenUtils.py 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import time
  2. import jwt
  3. JWT_TOKEN_EXPIRE_SECONDS = 3600 * 24 * 7 # token有效时间 7天
  4. JWT_TOKEN_SECRET_SALT = 'jasonphd.2024.ttb'
  5. JWT_TOKEN_ALGORITHM = 'HS256' # HASH算法
  6. def generate_jwt_token(user: str) -> str:
  7. """根据用户id生成token"""
  8. data = {'user_id': user, 'exp': int(time.time()) + JWT_TOKEN_EXPIRE_SECONDS}
  9. print("generate data:", data)
  10. jwtToken = jwt.encode(data, JWT_TOKEN_SECRET_SALT, algorithm=JWT_TOKEN_ALGORITHM)
  11. return jwtToken
  12. def verify_jwt_token(user: str, jwtToken: str) -> bool:
  13. """验证用户token"""
  14. data = {'user_id': user}
  15. try:
  16. payload = jwt.decode(jwtToken, JWT_TOKEN_SECRET_SALT, algorithms=[JWT_TOKEN_ALGORITHM])
  17. print("verify:", payload)
  18. exp = int(payload.pop('exp'))
  19. if time.time() > exp:
  20. print('已失效')
  21. return False
  22. return data == payload
  23. except jwt.exceptions.ExpiredSignatureError as ex:
  24. print('token签名过期:', ex)
  25. except jwt.PyJWTError as ex:
  26. print('token解析失败:', ex)
  27. return False