util_jwt.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import jwt
  2. # from jwt import exceptions
  3. import datetime
  4. def jwt_encoding(payload):
  5. SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
  6. headers = {
  7. 'typ': 'jwt',
  8. 'alg': 'HS256'
  9. }
  10. return jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers)
  11. def jwt_decoding(token):
  12. SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
  13. payload = None
  14. msg = None
  15. try:
  16. payload = jwt.decode(token, SALT, True)
  17. msg = "token认证成功"
  18. # except exceptions.ExpiredSignatureError:
  19. # msg = "超时错误,token已失效"
  20. except jwt.DecodeError:
  21. msg = "token认证失败"
  22. except jwt.InvalidTokenError:
  23. msg = "非法token"
  24. return {"payload": payload, "msg": msg}
  25. def create_token_for_login(payload, timeout=1):
  26. SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
  27. headers = {
  28. 'typ': 'jwt',
  29. 'alg': 'HS256'
  30. }
  31. payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(days=timeout)
  32. token = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers).decode('utf-8')
  33. return token
  34. """
  35. try:
  36. # 从token中获取payload【不校验合法性】
  37. # unverified_payload = jwt.decode(token, None, False)
  38. # print(unverified_payload)
  39. # 从token中获取payload【校验合法性】
  40. verified_payload = jwt.decode(token, SALT, True)
  41. return verified_payload
  42. except exceptions.ExpiredSignatureError:
  43. print('token已失效')
  44. except jwt.DecodeError:
  45. print('token认证失败')
  46. except jwt.InvalidTokenError:
  47. print('非法的token')
  48. """