We are currently in the process of transitioning our frontend to a separate project outside of Django. This project will be a JavaScript single page application.
One of the main reasons for this move is to simplify the workflow for our frontend developers. They will no longer need to run the entire project, including the API, locally. Instead, we have set up a test API for them to communicate with.
While we have resolved most of the CORS/CSRF issues that arose during this transition, we have encountered a new challenge that I have not been able to find a solution for despite extensive research and reading various resources.
Our frontend and API are hosted on different domains (during development localhost
and api-test.example.com
). Previously, when they were on the same domain, the frontend was able to access the CSRF token from the csrftoken
cookie set by the API (which is built on Django). However, with them now on separate domains, the frontend (localhost
) cannot access the API's cookies (api-test.example.com
).
I am exploring potential workarounds to deliver the CSRF token to the frontend. The Django documentation suggests setting a custom X-CSRFToken
header for AJAX requests. Would exposing this header in every response compromise the CSRF protection if we allow the frontend to read it via Access-Control-Expose-Headers
?
Considering that we have configured CORS properly for the API (restricting cross-origin requests to specific domains), third-party sites should not be able to access this response header through JavaScript, thus preventing any unauthorized AJAX requests on behalf of our users. Am I overlooking any critical aspects here?
Alternatively, is there a more effective approach to achieve our objectives?