Django REST框架禁止的CSRF cookie未设置

时间:2017-07-02 20:56:23

标签: django cookies django-rest-framework

我有这个观点

from rest_framework import parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import EmailUserSerializer
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt


@method_decorator(csrf_exempt, name='post')
class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = AuthTokenSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        user_serializer = EmailUserSerializer(user)
        return Response({'token': token.key, 'user': user_serializer.data})


obtain_auth_token = ObtainAuthToken.as_view()

和这个网址

urlpatterns = [
    url(r'^login/$',views.obtain_auth_token, name='get_auth_token'),
    url(r'^login2/$',ObtainAuthToken, name='get_auth_token'),
]

我试图像这样邮寄帖子:

127.0.0.1:8000/api/login2/

但我只能收到此错误

Forbidden (CSRF cookie not set.): /api/login2/
[02/Jul/2017 22:49:11] "POST /api/login2/ HTTP/1.1" 403 2891

我知道有数百个这样的帖子,我搜索了很长时间的解决方案,但似乎没有任何工作

像这样试试

urlpatterns = patterns('',
    url('^login2/$', csrf_exempt(ObtainAuthToken)),
    ...
)

from django.utils.decorators import method_decorator
class LoginView(APIView):
   @method_decorator(csfr_exempt)
   def dispatch(self, *args, **kwargs):
       ...

还有这个

from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class LoginView(APIView):
       ...

和这个

@method_decorator(csrf_exempt, name='post')
class ObtainAuthToken(APIView):
    throttle_classes = ()
    ...
    @csrf_exempt
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)

1 个答案:

答案 0 :(得分:3)

您需要使用ObtainAuthToken.as_view()。任何APIView都会自动使用csrf_exempt()(如果您使用的是SessionAuthentication,则会明确检查CSRF令牌),但如果您不使用.as_view()则无效。您不必在csrf_exempt之上明确使用APIView

我不确定你为什么不使用第一个网址/login/,但是如果你遇到了这个网址的问题,你就会采用错误的方法修复它们。

旁注:csrf_exempt设置函数的属性。因此,在post()上使用它绝对没有效果,因为中间件不会检查post()方法上的属性。您需要在dispatch()方法或csrf_exempt(ObtainAuthToken.as_view())上使用它。