laravel的中间件可以传递token数据到控制器,django如何从中间件传递数据到具体函数?

import time

import jwt
from django.conf import settings
from django.http import JsonResponse


class JwtMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        response = self.get_response(request)
        if request.path in settings.API_ROUTE_WHITE_LIST:
            return response
        else:
            token = request.META.get('HTTP_AUTHORIZATION')
            if token is not None:
                token = token.replace('Bearer ', '')
                try:
                    decode = jwt.decode(token, settings.JWT_TOKEN, algorithms=['HS256'])
                    exp = decode['exp']
                    if int(time.time()) > exp:
                        # token过期了
                        jwt_obj = dict()
                        jwt_obj['code'] = 400002
                        jwt_obj['info'] = 'Token Expired!'
                        return JsonResponse(jwt_obj, safe=False)
                    else:
                        response['a']=100
                        return response
                except (jwt.exceptions.InvalidSignatureError, jwt.exceptions.DecodeError):
                    jwt_obj = dict()
                    jwt_obj['code'] = 400003
                    jwt_obj['info'] = 'Token Verify Failed'
                    return JsonResponse(jwt_obj, safe=False)

            else:
                jwt_obj = dict()
                jwt_obj['code'] = 400003
                jwt_obj['info'] = 'Token Verify Failed'
                return JsonResponse(jwt_obj, safe=False)
阅读 1.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题