1.新建middleware.py
from django.urls import reverse
from rest_framework.response import Response
from utils.token import check_token
from django.http import JsonResponse, HttpResponseRedirect
from yshop.models import MyUser
try:
from django.utils.deprecation import MiddlewareMixin # Django 1.10.x
except ImportError:
MiddlewareMixin = object
# 白名单,表示请求里面的路由时不验证登录信息
API_WHITELIST = ['/login/’]
class AuthorizeMiddleware(MiddlewareMixin):
def process_request(self, request):
print("INFO: middleware process request.")
print("INFO: request url: ", request.path)
if not any(api in request.path for api in API_WHITELIST):
# if request.path not in API_WHITELIST:
# 从请求头中获取 username 和 token
userid = request.META.get('HTTP_USERNAME')
token = request.META.get('HTTP_AUTHORIZATION')
print('mid-userid', userid)
print('mid-token', token)
if userid is None or token is None:
print('ERROR: 未查询到登录信息')
return JsonResponse({'code': 404, 'msg': '未查询到登录信息'})
else:
user_info = MyUser.objects.filter(token=token)
if not user_info.exists():
return JsonResponse({'code': 403, 'msg': '未找到token信息'})
# 调用 check_token 函数验证
if check_token(userid, token):
pass
else:
print('Error: 登录信息错误或已过期')
return JsonResponse({'code': 403,
'msg': '登录信息错误或已过期'})
2.在settings.py中配置中间件:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'Myproject.middleware.AuthorizeMiddleware',
]
注意哦,跨域的中间件必须放在第一个!