Django CSRF when the backend and interface are separated

After searching the Internet, people usually deal with this situation - the interface module is generated by the django view function, which can send the user a csrf token cookie. When a user has a server request using ajax, people can rewrite the ajaxSend behavior sending the csrf server.

However, my situation is that my interface is completely separate from the inside, i.e. my interface is on a dedicated server with nginx, and I only have one html containing all the different pages using hashbang. My server runs on different servers using a different domain name, and in this case, how does the client receive the csrf cookie? My back-end provided only json api return.

Thanks.

+6
source share
2 answers

If you look at the source of the CRSF token: you will see that all csrf_middleware checks the cookie for the post value. you just need to return the post value to your server, as the cookie should already be set as ajax. If you look at the source of the template tag, you will see that it simply wraps the variable from the context. Either insert it into the response, pulling it out of context, if available, or directly invoking the context processor. Now you just need to send it back as a crsf_token POST variable,

0
source

Suppose the interface has frontend.example.com and backend domain backend.example.com. (If you are something like a Django rest framework) If you can use two methods, you can enable the ie ,. CSRF or CORS protection

For CORS,

pip install django-cors-headers 

and then set this to INSTALLED_APPS, MIDDLEWARE_CLASSES and add the external domain to CORS_ORIGIN_WHITELIST.

 CORS_ORIGIN_WHITELIST = ( 'frontend.example.com' ) 

CORS blocks any HTTP request originating from any domain other than frontend.example.com


For CSRF,

 CSRF_COOKIE_DOMAIN = ".mydomain.com" 

and if you are using an Angular app, follow these steps:

 $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.withCredentials = true; 

and then add the headers and then make an http request.

 headers : { "x-csrftoken" : $cookies.csrftoken } 
0
source

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


All Articles