CSRF - Referer when performing ajax request from chrome extension with Django Backend
Asked Answered
V

0

8

I am using the latest versions of Django and Django Rest Framework. My web application provide an API that is used currently by the front end only.

I am on the process to create a chrome extension using the same API routes.

When I use the local server runserver command, I have no issue. When the server is runned behind HTTPS I consistently have 403 errors.

{"detail":"CSRF Failed: Referer checking failed - no Referer."}

The view I used is the following:

@method_decorator(csrf_exempt, name='dispatch')
class ObtainAuthToken(APIView):
    permission_classes = (AllowAny,) #maybe not needed in your case

    def post(self, request):
        username = request.POST['username'].lower()
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        payload = dict()

        if user is not None:

            token, created = Token.objects.get_or_create(user=user)

            payload['token'] = token.key
            payload ["success"] = True

        else:
            payload['error'] = "Credentials not valid or user inactive"
            payload ["success"] = False

        payload["operation"] = "Obtain Authentication Token"
        payload ["timestamp"] = get_timestamp()
        return Response(payload)

The AJAX Call is the following:

$.ajax({
            url: endpoint + "api/1.0/get_auth_token/",
            type: 'POST',
            // Fetch the stored token from localStorage and set in the header
            data: formData,
            dataType: "json",
            mimeType: "multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            xhrFields: {
              withCredentials: false
            },
            headers: {
                 'Cache-Control': 'no-cache'
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-CSRFToken', csrf_val);
            },
            success: function(response){
                console.log(response);
            }
 });

The weird thing is it perfectly works in every situation when I use Postman. I set the headers to be identical and I still can't make it work.

Thanks for your help

Vomit answered 5/9, 2017 at 10:9 Comment(2)
Any news about it?Devoirs
Where did you place this Ajax code, in which file?Oletta

© 2022 - 2024 — McMap. All rights reserved.