【发布时间】:2017-10-06 07:30:21
【问题描述】:
我的代码有两个 mixin,BasicAuthMixin 和 JWTAuthMixin,如下所述。只需假设 self.authenticate 方法返回 True 并且不会引发任何异常:
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
class BasicAuthMixin(View):
"""
Add this mixin to the views where Basic Auth is required.
"""
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
try:
self.authenticate(request)
except:
return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json')
return super(BasicAuthMixin, self).dispatch(request, *args, **kwargs)
class JWTAuthMixin(View):
"""
Add this mixin to the views where JWT based authentication is required.
"""
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
try:
self.authenticate(request)
except:
return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json')
return super(JWTAuthMixin, self).dispatch(request, *args, **kwargs)
根据需要的身份验证在视图中使用这些 mixin。
实际问题从这里开始:我正在尝试创建另一个 mixin AllAuthMixin,当包含在任何视图中时,它将自动确定需要根据哪些 mixin 调用提供的身份验证标头:
class AllAuthMixin(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
auth = request.META.get('HTTP_AUTHORIZATION') or ''
if auth.startswith('Bearer'):
return JWTAuthMixin.as_view()(request, *args, **kwargs)
elif auth.startswith('Basic'):
return BasicAuthMixin.as_view()(request, *args, **kwargs)
raise Exception('Unauthorized Access to Saurav APIs', 403)
一旦我在任何视图中包含 AllAuthMixin 说 /test 它实际上会调用适当的 Mixins 但返回 Method Not Allowed (GET): /test
我调试并发现如果我使用基本身份验证,Method Not Allowed 错误消息来自以下行:
return super(BasicAuthMixin, self).dispatch(request, *args, **kwargs)
以下说明了一个非常简单的示例,可以使用基本身份验证调用我的视图:
>>> import requests
>>> requests.get('http://127.0.0.1:8000/test', auth=('UserName', 'Password'))
<Response [405]>
我不确定我在这里做错了什么。谁能帮我解决这个问题或任何替代方法来实现这一目标。我想要的是重用已经声明的 mixins:BasicAuthMixn 和 JWTAuthMixin。
【问题讨论】:
标签: django mixins django-class-based-views