Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF Exempt Failure - APIView csrf django rest framework

I have the following code:

The problem is when I try to access user-login/ I get an error: "CSRF Failed: CSRF cookie not set."

What can I do?

I am using the django rest framework.

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
like image 528
user2237822 Avatar asked May 11 '13 21:05

user2237822


People also ask

How do I exempt CSRF token in Django?

How do I exempt CSRF token in Django? By setting the cookie and using a corresponding token, subdomains will be able to circumvent the CSRF protection. The only way to avoid this is to ensure that subdomains are controlled by trusted users (or, are at least unable to set cookies).

Does REST framework need CSRF token specify your answer *?

Does REST framework need CSRF token specify your answer *? If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST , PUT , PATCH or DELETE operations. In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

What does CSRF exempt mean?

If you add @csrf_exempt to the top of your view, then you are basically telling the view that it doesn't need the token. This is a security exemption that you should take seriously.

What are CSRF and Django prevent it?

Django features a percent csrf token percent tag that is used to prevent malicious attacks. When generating the page on the server, it generates a token and ensures that any requests coming back in are cross-checked against this token. The token is not included in the incoming requests; thus they are not executed.


2 Answers

I assume you use the django rest framework SessionBackend. This backend does a implicit CSRF check

You can avoid this by:

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)

And set this as authentication_classes in your View

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("/")
like image 175
maersu Avatar answered Oct 24 '22 23:10

maersu


Actually, better way to disable csrf check inside SessionAuthentication is:

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication

class SessionAuthentication(OriginalSessionAuthentication):
    def enforce_csrf(self, request):
        return
like image 30
Alexander Artemenko Avatar answered Oct 24 '22 23:10

Alexander Artemenko