Contents

jwt 生成与验证 - Python

Contents

生成与验证

data: 自定义数据, 如 {'username':user_name, 'user_id': user_info.id}

验证通过后在payload中获取

import jwt
from datetime import datetime,timedelta

SECRECT_KEY = b'\x92R!\x8e\xc6\x9c\xb3\x89#\xa6\x0c\xcb\xf6\xcb\xd7\xc'

def genToken(data):
  expInt = datetime.utcnow() + timedelta(days=1)
  iat = datetime.utcnow()
  payload = {
    'exp': expInt,
    'iat': iat,
    'data': data 
    }
  token = jwt.encode(payload, key = SECRECT_KEY, algorithm='HS256')
  return bytes.decode(token)

def verfiyToken(tokenStr):
  try:
    if tokenStr is not None:
      tokenBytes =  tokenStr.encode('utf-8')
      payload = jwt.decode(tokenBytes,SECRECT_KEY)
      return payload
    return None
  except jwt.PyJWTError as e:
    print("jwt验证失败: %s" % e)
    return None