2017-07-02 77 views
0

我有這種說法Django的REST框架故宮CSRF的cookie沒有設置

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 

我知道有數百個職位這樣的,我搜索了很久一個解決方案,但似乎沒有任何工作

tryied這樣

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): 
     ... 

and this

@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) 
+0

嘗試'@method_decorator(csrf_exempt,name ='post')' - >'@ csrf_exempt' ...看看是否可以解決它? –

+0

你的意思是? @method_decorator(csrf_exempt,名稱= '後') 類ObtainAuthToken(APIView): throttle_classes =()... @csrf_exempt 高清張貼(個體經營,要求,* ARGS,** kwargs): 串行= self.serializer_class(data = request.data) ... 仍然沒有工作 –

回答

3

您需要使用ObtainAuthToken.as_view()。任何APIView自動使用csrf_exempt()(並且如果您使用的是SessionAuthentication,則顯式檢查CSRF令牌),但如果您未使用.as_view(),那麼這將不起作用。您不必在APIView的作用之上明確使用csrf_exempt

我不確定你爲什麼不使用第一個網址/login/,但是如果你有這個網址的問題,你會錯誤地修復它們。

附註:csrf_exempt在功能上設置了一個屬性。因此,在post()上使用它是完全沒有效果的,因爲中間件不會檢查post()方法的屬性。您需要在dispatch()方法或csrf_exempt(ObtainAuthToken.as_view())上使用它。

+0

這實際上是拯救我的一天! btw即時通訊不使用第一次登錄,因爲我試圖實現一個不同的版本......現在它很好的感謝as_view()!謝謝 –

相關問題