CSRF and CORS with Django (REST Framework)

We are in the process of moving our interface into a separate project (from Django). This is a one page Javascript application.

One reason is to make it easier for our third-party developers to work without having to complete the entire project, including the API, locally. Instead, we would like them to be able to communicate with the test API that we installed.

We managed to solve most of the CORS / CSRF problems. But now we are faced with something that I can’t find a solution anywhere, despite reading a lot of documentation and SO answers.

The interface and API are served from different domains (during development localhostand test-api.example.com). Until now, while it was serving from the same domain, the interface managed to get the CSRF token from the cookie csrftokenset by the API (Django). But when serving from different domains, the interface ( localhost) cannot access cookies API ( api-test.example.com).

I am trying to find a way around this in order to somehow deliver the CSRF token to the external interface. Django docs recommend setting a custom X-CSRFTokenheader for AJAX requests. Could we jeopardize CSRF protection if we equally served the CSRF token in each response as a header and (through Access-Control-Expose-Headers) allowed this header to be read by the interface?

Given that we correctly configured CORS for the API (i.e., allow certain domains to execute requests with cross-originating APIs), JS on third-party sites will not be able to read this response header, therefore it will not be able to compromise AJAX requests behind our users, is not it is it? Or did I miss something important here?

Or is there another, better way to achieve what we want?

+4
source share
2 answers

, : CSRF cookie , ( CORS). , , cookie , , .

, , cookie: . , meta. , , - .

, , . , , CORS Access-Control-Expose-Headers.

, CSRF. - - : " CSRF , ",.

(, , Django CSRF SPA. . , , , .)

+1

, corsheaders. Django MIDDLEWARE:

from django.utils.deprecation import MiddlewareMixin

class CsrfHeaderMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if "CSRF_COOKIE" in request.META:
            # csrfviewmiddleware sets response cookie as request.META['CSRF_COOKIE']
            response["X-CSRFTOKEN"] = request.META['CSRF_COOKIE']
        return response

:

 CORS_EXPOSE_HEADERS = ["X-CSRFTOKEN"]

API GET JS, X-CSRFTOKEN , , POST PUT PATCH DELETE .

0

Source: https://habr.com/ru/post/1694788/


All Articles