简体   繁体   中英

Django DRF with React: How to obtain CSRF cookie?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM