1.创建文件jwt_utils
2.导入
import jwt
from datetime import datetime,timedelta
from flask import current_app,jsonify,g
3.生成token
def generate_token(payload,expiry): """生成token""" # datetime.utcnow()当前时间 # timedelt是从当前时间的偏差值 _payload = { "exp":expiry, # 有效期2个小时 } _payload.update(payload) print("更新后payload>>>>>", _payload) # 读取配置文件中的secret_key _key = current_app.config.get('SECRET_KEY') # 生成的token是使用默认有效期 # 返回的是string 类型的: xxxAsasdas.JWFIIASFBH.qwawefansdvjk token = jwt.encode(payload=_payload, key=_key) return token
4.校验token
def verify_token(token):
"""校验token"""
# 读取配置文件中的secret_key
_key = current_app.config.get('SECRET_KEY')
try:
# 返回的是{}格式的字符串
payload = jwt.decode(token, key=_key,algorithms=['HS256'])
print("效验payload>>>", payload)
return payload
except Exception as e:
print("验证token失败,原因是>>",e)
return jsonify(msg="token验证失败",code=401)
5.生成token和刷新token
# def _generate_token(username,user_id refresh=True):
def _generate_token(payload, refresh=True):
print('用户信息0000', payload)
g.payload = '',
g.payload = payload
print('用户信息',g.payload)
"""生成token和刷新token"""
expiry = datetime.utcnow() + timedelta(seconds=15)
# 生成token, 默认2小时
token = "JWT " + generate_token(payload,expiry)
if refresh:
# 刷新生成新token
expiry = datetime.utcnow() + timedelta(days=15)
# is_refresh作为更新token的信号
payload.update({'is_refresh': True})
print("_generate_token中的payload--->", payload)
refresh_token = generate_token(payload,expiry)
print("refresh_token>>>>", refresh_token)
else:
refresh_token = None
return token, refresh_token
6.生成token
def refresh_new_token():
"""
生成新token
"""
payload = {
'is_refresh':True
}
_, new_token = _generate_token(payload)
print('新的token',new_token)
return new_token
7.在登录视图中使用
from jwt_utils import _generate_token
# 生成token,返回token
token, refresh_token = _generate_token({'account': user.account, 'user_id': user.uid})
data = {
'code':200,
'message': '登录成功',
'data': {'token': token, 'refresh_token': refresh_token, 'account': user.account,'uid': user.uid}