程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django simple JWT auto renewal policy

編輯:Python

programme

1. Return to the front end after login token And set the expiration time 30 minute , Each time a request is made, the front end puts token It is stored in the request header to send a request , When the back-end receives a request, it gets the request header for processing jwt Analyze and judge whether the expiration time is less than 30 minute , If it is less than 30 Minutes to generate a new token stay responseHearde Just go back
2. When a user triggers an event , Using middleware , Back end detection found token It's almost time to expire ,
Generate a new token as well as refresh_token , to update redis In the cache token Information ,
Back front end request Header Set in the token remain unchanged , Verify the validity of the in the cache token Subject to

The first scheme I use here
middleware

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):
# The expiration time in the cache is the same as The current timestamp is subtracted Less than or equal to this Number of configurations
token_obj,time_remaining = ts.output_time_remaining(auth_token)
if time_remaining <= config.HALF_HOUR:
refresh_token = token_obj["refresh_token"]
# Based on the refresh token to update
data = ts.update_token(refresh_token)
# Join the response In the head
response["NEW_HTTP_AUTHORIZATION"] = data["token"]
expire_time1 = ts.output_expire_time()
# Will be new token Join in cache
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:
# Give the original token Set up The blacklist
cache.set(auth_token+config.JWT_BLACK_LIST_TAG, "user_id", time_remaining+config.REDIS_TOKEN_PAST_DUE_TIME)
# Delete in cache primary token
cache.delete(auth_token)
return response

The specific overall code is not written in detail
Overall flow chart :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved