0

I have a React frontend running at frontend.example.com and a Django backend with DRF running at backend.example.com. I am using Django Session Authentication and I want to properly implement CSRF protection.

Taking the React login page frontend.example.com/login as an example. It's the first time for a user to visit the page. There is a form with a user and password and on submit a new POST request is created to the Django backend. To the best of my knowledge, the CSRF token cookie should already be included in this request, right?

How to obtain that CSRF token from the Django backend? I am thinking of doing a GET request to the Django backend on loading the login-page to obtain that CSRF token cookie. Is that the way to do it or is there any other best practice?

RaideR
  • 869
  • 1
  • 12
  • 33

1 Answers1

0

Django has a section for AJAX request and how to handle CSRF: AJAX

Using this method you should send the token over and over again for each post request. The other method is using CORS. in this method, you only respond to the domains that you already whitelisted with headers that are whitelisted as well. So, instead of getting and passing CSRF token, you check if the request is coming from the right domain and then you can respond to it. And combining with a token system for user authentication, you should be good.

You can use this package for handling CORS if you use DRF: django-cors-headers

Using rate limiting can also help you avoid spams and robots to do noticeable harm.

Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26
  • Thank's for your answer! I read the AJAX request CSRF section that you linked to but I do not understand how to initially receive the CSRF token for my form without doing any request at all. I am already using CORS, so any request to my backend comes from `frontend.example.com`. – RaideR May 02 '20 at 14:33
  • Django will add the token in a cookie if you're using the built-in template engine but it might not be available if you render your forms dynamically which you usually do using react. Also, you post data using JSON which can't be used with csrf token. If you're using django to render form, then csrf is available on user cookie, otherwise, you don't need it and CORS should be enough. – Navid Zarepak May 02 '20 at 14:40
  • you can find examples here: https://stackoverflow.com/questions/50732815/how-to-use-csrf-token-in-django-restful-api-and-react – Navid Zarepak May 02 '20 at 14:41
  • Why cant I add a CSRF cookie to my POST JSON data or send the CSRF token in the request header? – RaideR May 02 '20 at 15:01
  • check here for more details and how to do it if you really want: https://security.stackexchange.com/questions/170477/csrf-with-json-post-when-content-type-must-be-application-json – Navid Zarepak May 02 '20 at 15:04
  • Hi RaideR! Did you ever find the solution? I am facing a similar problem.... – Fabian Omobono Mar 23 '21 at 15:08