Reputation: 387
Im developing an application with two core. Client Side with ReactJs and a Server Side made with Django.
The Client will makes a lot of GET/POST request to the server. To prevent CSRF problem, every Ajax Request has CSRF-TOKEN.
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", window.csrftoken);
}
[...]
}
This is a piece of the Django/Python view view example of the server:
response = HttpResponse(json.dumps(software_settings), content_type="application/json" )
response['Access-Control-Allow-Origin'] = "*";
response['Access-Control-Allow-Headers'] = "X-Requested-With, X-Prototype-Version, X-CSRF-Token";
response['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS";
I have two big problems:
FIRST: On online solutions, window.csrftoken variables is usually taken from cookie. I sincerely don't know how to create it. Im using unversal-cookie to read and write cookie with React, but I missing the correct data flow between the two applications. The default values is "null" so the first call has null as CRFT Token;
SECOND: I have a problem with response. As see above, I've tried to put a lot of configurations entry fro Access-Control. This is a piece of request headers:
Access-Control-Request-Headers:x-csrftoken
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:3000
This is the error I get:
Failed to load http://localhost:8000/get_software_settings/:
Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response.
I think Im missing something considering the flow of the application. Consider one last thing: In production, the reactjs app will be compiled to be put in the same server as django application (apache).
Thanks you for any advice.
Upvotes: 1
Views: 1226
Reputation: 166
Django generate and serve the CSRFToken Django CSRF protection, react take it and pass it when make the POST request, usually a form submit.
So if you want to follow this solution make the first request from react to django to generate the CSRFToken and consume it in the view.
However i have a similar development context and i use Django Rest Framework without CSRFToken, make a normal login in django and in every call from react to Django i pass the session cookies (using the withCredencial parameter) to check if the user is authenticated.
Upvotes: 1