2013-05-11 24 views
8

私は、次のコードを持っている:CSRF免除失敗 - APIView CSRFジャンゴ残りのフレームワーク

問題は、私は、ユーザーのログインにアクセスしようとする/私はエラーを取得する次のとおりです。 「CSRFは失敗しました:CSRFのクッキーが設定されていません。」

どうすればよいですか?

私はdjango restフレームワークを使用しています。

urls.py: 

url(r'^user-login/$', 
    csrf_exempt(LoginView.as_view()), 
    name='user-login'), 

views.py: 

class LoginView(APIView): 
""" 
List all snippets, or create a new snippet. 
""" 
def get(self, request, format=None): 
    startups = Startup.objects.all() 
    serializer = StartupSerializer(startups, many=True) 
    return Response(serializer.data) 

def post(self, request, format=None): 
    profile = request.POST 

    if ('user_name' not in profile or 'email_address' not in profile or 'oauth_secret' not in profile): 
     return Response(
      {'error': 'No data'}, 
      status=status.HTTP_400_BAD_REQUEST) 

    username = 'l' + profile['user_name'] 
    email_address = profile['email_address'] 
    oauth_secret = profile['oauth_secret'] 
    password = oauth_secret 

答えて

14

あなたはdjango rest framework SessionBackendを使用すると仮定します。このバックエンドは、あなたがすることによってこれを回避することができimplicit CSRF check

ん:

from rest_framework.authentication import SessionAuthentication 

class UnsafeSessionAuthentication(SessionAuthentication): 

    def authenticate(self, request): 
     http_request = request._request 
     user = getattr(http_request, 'user', None) 

     if not user or not user.is_active: 
      return None 

     return (user, None) 

そして、あなたのビューでauthentication_classesよう

class UnsafeLogin(APIView): 
    permission_classes = (AllowAny,) #maybe not needed in your case 
    authentication_classes = (UnsafeSessionAuthentication,) 

    def post(self, request, *args, **kwargs): 

     username = request.DATA.get("u"); 
     password = request.DATA.get("p"); 

     user = authenticate(username=username, password=password) 
     if user is not None: 
      login(request, user) 

     return redirect("/") 
9

これを設定するには、実際には、SessionAuthentication内CSRFチェックを無効にする良い方法は次のとおりです。

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication 

class SessionAuthentication(OriginalSessionAuthentication): 
    def enforce_csrf(self, request): 
     return 
2

この問題を解決する最も簡単な方法LEM:認証の2つの方法がDRFであることsee drf auth

については

BasicAuthentication

SessionAuthentication(デフォルト)

SessionAuthenticationは強制CSRFチェックを持っていますが、BasicAuthenticationはしていません。 私の方法は、SessionAuthenticationの代わりに私のビューでBasicAuthenticationを使用しています。

from rest_framework.authentication import BasicAuthentication 

class UserLogin(generics.CreateAPIView): 
    permission_classes = (permissions.AllowAny,) 
    serializer_class = UserSerializer 
    authentication_classes = (BasicAuthentication,) 

    def post(self, request, *args, **kwargs): 
     return Response({})