当前位置:网站首页>Disable the token and update the token function without awareness
Disable the token and update the token function without awareness
2022-08-03 03:03:00 【qishaoawei】
禁用token
禁用tokenIn layman's terms, it is saved to the browser after logging intokenAlso save to when logging outredis里
Then use the hook function to judge once before each request,If requested againtoken与redis里的token进行对比
If both have been statedtoken没有更新,很可能是tokenLeaks are used maliciously,
So disable it every time you exittoken
Immediately after a forced login implementation disabletoken
Created in a blueprint within the project
@user_dp.before_app_request
def gz(): #钩子函数 Called before every request
rep = reqparse.RequestParser()
rep.add_argument('token', location='headers')
args = rep.parse_args()
token = args['token']
payload = JwtTool().valid(token) #解密token
## Put it into the hook function to verifytoken是否存在
rds = SmsTool().rds # 已经封装好的redis数据库信息
is_exists = rds.exists('token_%s' % token)
rds.close()
if is_exists:
g.uid = -1
else:
try:
g.uid=payload['uid']
except Exception as a:
print(a)
g.uid=0
def login(func):
def warpper(*args,**kwargs):
#判断用户是否登录
uid=g.uid
if uid==0:
return jsonify({
'code':403,
'msg':'用户未登录'
})
elif uid==-1: #验证token是否在redis里面
return jsonify({
'code':400,
'msg':'token被禁用'
})
return func(*args,**kwargs)
return warpper
#退出登录 Front-end logout calls this first 然后再清空token
class TokenView(Resource):
@login
def post(self):
rep = reqparse.RequestParser()
rep.add_argument('token', location='headers')
args = rep.parse_args()
token = args['token']
rds=SmsTool().rds #已经封装好的redis数据库信息
rds.set('token_%s'%token,'1',ex=3600)
rds.close()
return jsonify({
'code':200,
'msg':'退出成功'
})
api.add_resource(TokenView,'/token') #退出
无感知更新token
无感知更新token就是tokenThe validity period is not long to be safe,requires frequent updates,It's a lot easier to just let it update itself
Write in the logged in blueprint
@user_dp.before_app_request
def gz():
rep = reqparse.RequestParser()
rep.add_argument('token', location='headers')
args = rep.parse_args()
token = args['token']
payload = JwtTool().valid(token)
## Put it into the hook function to verifytoken是否存在
rds = SmsTool().rds # 已经封装好的redis数据库信息
is_exists = rds.exists('token_%s' % token)
rds.close()
if is_exists:
g.uid = -1
else:
try:
g.uid=payload['uid']
except ExpiredSignatureError:
g.uid=-2 #If there are other errors reported-2
except Exception as a:
print(a)
g.uid=0
def login(func):
def warpper(*args,**kwargs):
#判断用户是否登录
uid=g.uid
if uid==0:
return jsonify({
'code':403,
'msg':'用户未登录'
})
elif uid==-1: #验证token是否在redis里面
return jsonify({
'code':400,
'msg':'token被禁用'
})
elif uid==-2: #Verify that it has expired
return jsonify({
'code':666,
'msg':'token已过期'
})
return func(*args,**kwargs)
return warpper
class LoginView(Resource): #登录
def post(self):
rep=reqparse.RequestParser()
rep.add_argument('phone')
rep.add_argument('password')
args=rep.parse_args()
user_info=UserModel2.query.filter(UserModel2.mobile==args['phone']).first()
if not user_info:
return jsonify({
'code':400,
'msg':'The user's mobile phone number does not exist'
})
if user_info.password!=args['password']:
return jsonify({
'code':400,
'msg':'密码不正确'
})
token=JwtTool().create({
#短token
'username':user_info.username,
'uid':user_info.id,
'exp':int(time.time()+360) #Plus an expiration date360秒
})
long_token=JwtTool().create({
#长token
'username':user_info.username,
'uid':user_info.id,
'long':True, #This flag is used to distinguish longtoken的 目的是让tokenVerification of common interfaces cannot be performed Only used for verification of specific interfaces
'exp':int(time.time()+15*24*3600) #Plus an expiration date15天
})
return jsonify({
'code':200,
'msg':'登陆成功',
'data':{
'username':user_info.username,
'token':token, #短token #Both are saved when logging in
'long_token':long_token #长token
}
})
#退出登录 Front-end logout calls this first 然后再清空token
class TokenView(Resource):
def put(self): #更新token
#获取参数
rep = reqparse.RequestParser()
rep.add_argument('longtoken', location='headers')
args = rep.parse_args()
#校验参数
try:
payload=JwtTool().valid(args['longtoken']) #Encapsulated decryptiontoken
except Exception as a:
return jsonify({
'code':403,
'msg':'用户未登录'
})
#逻辑
user_info = UserModel2.query.get(payload['uid'])
#再生成token
token = JwtTool().create({
# Take advantage of package generationtoken函数
'username': user_info.username,
'uid': user_info.id,
'exp': int(time.time() + 360) # Plus an expiration date360秒
})
#返回响应
return jsonify({
'code':200,
'msg':'token更新成功',
'data':{
'token':token
}
})
前端在main.js里进行编写
//强制登录
axios.interceptors.response.use(function(resp){
console.log('resp===',resp) //resp It is the data returned by the request response
// 未登录用户 直接跳转到登录页面
if(resp.data.code==403){
router.push('/login') //此处无法使用 this.$router
}
return resp //Return the request object back
},function(error){
console.log(error)
})
// 无感知更新token
axios.interceptors.response.use(function(resp){
console.log(resp)
if(resp.data.code==666){
// 代表token过期了
//重新请求token
reloadToken()
}
return resp
},function(error){
console.log(error)
})
//重新加载token
function reloadToken(){
axios.put('/user/token',{
},{
'headers':{
'longtoken':localStorage.getItem('long_token')
}
}).then((result) => {
if (result.data.code==200){
localStorage.setItem('token',res.data.data.token)
window.location.reload() //网页刷新
}
}).catch((err) => {
console.log(err)
});
}
边栏推荐
猜你喜欢
OpenWRT设置ipv6网络
.NET深入解析LINQ框架(四:IQueryable、IQueryProvider接口详解)
孩子坐不住就是不专注?猿辅导揭秘专注力的三大误区
一些面试的总结
JVM内部结构图及各模块运行机制总结
华为防火墙双机热备技术:HRP、VGMP、VRRP,三大技术值得一学!
SAP ABAP OData 服务如何支持修改(Update)操作试读版
Incorrect datetime value: ‘2022-01-01‘ for function str_to_date
国标GB28181协议EasyGBS平台项目现场通知消息过多导致系统卡顿该如何解决?
lombok 下的@Builder和@EqualsAndHashCode(callSuper = true)注解
随机推荐
torchvision.datasets.ImageFolder使用详解
10大领域5大过程47子过程快速记忆
MATLAB绘制填充图(X轴上下两种颜色)
flask-socketio实现websocket通信
力扣第二周错题集
46LVS+Keepalived群集
20、商品微服务-web层实现
暴力递归到动态规划 06 (剑指 Offer II 095. 最长公共子序列)
提高测试覆盖率的四大步骤
代码工具推荐
Introduction to agile development
超级复杂可贴图布局的初级智能文本提示器
容联云发送验证码
Latex-查看预收录在arXiv.org上论文的TeX源文件
浅谈敏捷开发
自己做的选择
Brute force recursion to dynamic programming 07 (516. Longest palindrome subsequence)
如何备考PMP才能一次通过?
initramfs详解----设备文件系统
Violent recursion to dynamic programming 06 (the sword refers to Offer II 095. Longest common subsequence)