栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

django simple jwt自动续期策略

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django simple jwt自动续期策略

方案

1.登录过后给前端进行返回token并设置了过期时间30分钟,每次请求的时候前端把token存在请求头里面进行发请求,后端接收请求的时候获取请求头出来进行jwt解析判断过期时间是否小于30分钟,如果小于30分钟就生成新的token在responseHearde进行返回即可
2.当某个用户触发事件时,使用中间件,后端检测发现token 快要到过期时间 ,
生成新的token以及refresh_token ,更新 redis缓存中的token信息,
后面前端请求Header中设置的token保持不变,校验有效性以缓存中的token为准

我这边用的第一种方案
中间件

from django.utils import deprecation
from xxxxxximport tools as ts
from django.core.cache import cache
from xxxxxximport settings as  config

class MyMiddleware(deprecation.MiddlewareMixin):
    def __init__(self, get_response=None):
        self.get_response = get_response

    def process_response(self, request, response):
        auth_token = request.META.get('HTTP_AUTHORIZATION')
        if auth_token:
            auth_token = auth_token[7:]
            if cache.get(auth_token):
                # 缓存中的过期时间与 当前时间戳相减 小于或等于该 配置数
                token_obj,time_remaining = ts.output_time_remaining(auth_token)
                if time_remaining <= config.HALF_HOUR:
                    refresh_token = token_obj["refresh_token"]
                    # 根据缓存中的 refresh token  更新
                    data = ts.update_token(refresh_token)
                    # 加入响应 头中
                    response["NEW_HTTP_AUTHORIZATION"] = data["token"]
                    expire_time1 = ts.output_expire_time()
                    # 将新token 加入 缓存
                    cache.set(data["token"],'{"refresh_token":'+f'"{refresh_token}"'+',"expire_time":'+str(expire_time1)+'}',config.UPDATE_FAILURE_TIME)
                    token_period_validity = int(cache.ttl(auth_token))
                    if token_period_validity:
                        # 给原来的 token 设置 黑名单
                        cache.set(auth_token+config.JWT_BLACK_LIST_TAG, "user_id", time_remaining+config.REDIS_TOKEN_PAST_DUE_TIME)
                        # 在缓存中删除 原token
                        cache.delete(auth_token)
        return response

具体整体代码就不细写
整体流程图 :

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983440.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号