浅析token原理
token:信息保存在浏览器,信息+签名密钥;服务端只负责对加密校验
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse
from app01 import models, tools
import json
class TokenMiddleware(MiddlewareMixin):
def process_request(self, request):
print(request.path)
if request.path in ['/login/',]:
return None
token = request.COOKIES.get('token_id')
if not token:
return redirect('login')
token_list = token.split('|')
if not tools.md5(token_list[0]) == token_list[1]:
return HttpResponse('无效的token')
def process_response(self, request, response):
if request.user.is_authenticated:
json_data = json.dumps({"user_id": f"{request.user.id}"})
token_key = tools.md5(json_data)
token = '|'.join([json_data, token_key])
response.set_cookie('token_id', token)
return response