123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import jwt
- # from jwt import exceptions
- import datetime
- def jwt_encoding(payload):
- SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
- headers = {
- 'typ': 'jwt',
- 'alg': 'HS256'
- }
- return jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers)
- def jwt_decoding(token):
- SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
- payload = None
- msg = None
- try:
- payload = jwt.decode(token, SALT, True)
- msg = "token认证成功"
- # except exceptions.ExpiredSignatureError:
- # msg = "超时错误,token已失效"
- except jwt.DecodeError:
- msg = "token认证失败"
- except jwt.InvalidTokenError:
- msg = "非法token"
- return {"payload": payload, "msg": msg}
- def create_token_for_login(payload, timeout=1):
- SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
- headers = {
- 'typ': 'jwt',
- 'alg': 'HS256'
- }
- payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(days=timeout)
- token = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers).decode('utf-8')
- return token
- """
- try:
- # 从token中获取payload【不校验合法性】
- # unverified_payload = jwt.decode(token, None, False)
- # print(unverified_payload)
- # 从token中获取payload【校验合法性】
- verified_payload = jwt.decode(token, SALT, True)
- return verified_payload
- except exceptions.ExpiredSignatureError:
- print('token已失效')
- except jwt.DecodeError:
- print('token认证失败')
- except jwt.InvalidTokenError:
- print('非法的token')
- """
|