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 :