pyjwt demo


# -*- coding:utf-8 -*-
import jwt
import datetime
from jwt import exceptions

from rbac.defind import JWT_SALT, JWT_TIMEOUT, JWT_ALGORITHM


def create_token(payload, timeout=JWT_TIMEOUT):
"""
:param payload: 例如:{'user_id':1,'username':'x'}用户信息
:param timeout: token的过期时间,
:return:
"""
headers = {
'typ': 'jwt',
'alg': JWT_ALGORITHM
}
payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
result = jwt.encode(payload=payload, key=JWT_SALT, algorithm=JWT_ALGORITHM, headers=headers)
return result


def parse_payload(token):
"""
对token进行和发行校验并获取payload
:param token:
:return:
"""
result = {'status': False, 'data': None, 'error': None}
try:
verified_payload = jwt.decode(token, JWT_SALT, JWT_ALGORITHM)
result['status'] = True
result['data'] = verified_payload
except exceptions.ExpiredSignatureError:
result['error'] = 'token已失效'
except jwt.DecodeError:
result['error'] = 'token认证失败'
except jwt.InvalidTokenError:
result['error'] = '非法的token'
return result
 
posted @ 2022-02-08 10:39  小学弟-  阅读(62)  评论(0编辑  收藏  举报