2013-05-11 4 views
8

я следующий код:CSRF Освобожденный Failure - APIView CSRF Джанго рамки остальные

Проблема заключается в том, когда я пытаюсь получить доступ пользовательский логин/я получаю сообщение об ошибке: «CSRF Ошибка: CSRF печенье не установлено.»

Что я могу сделать?

Я использую рамки для отдыха django.

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 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

На самом деле, лучший способ, чтобы отключить проверку CSRF внутри SessionAuthentication является:

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication 

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

Самый простой способ решить эту проблему Лем:

Для этого есть два способа аутентификации в ФПИ see drf auth

BasicAuthentication

SessionAuthentication (по умолчанию)

SessionAuthentication имеет принудительную проверку CSRF, но BasicAuthentication не делает. Итак, мой способ использует BasicAuthentication в моем представлении вместо SessionAuthentication.

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({}) 
Смежные вопросы