As for using the in-built Django forms for authentication, it cannot be done by passing JSON data. Instead, it is much better to create your own API endpoint and return some sort of authentication token to the client to use for future requests. In such cases, you might not need the CSRF token.
Alternatively, you could host your react app within a Django page, and use Django for authentication, in which case you don't need to handle the token as Django will do it for you. But this is not a very common approach and might not work in all cases.
As for injecting the CSRF token, there are a few different ways to do so when you are using ReactJS
Handling CSRF Tokens in React/Axios
For Axios client you have three options:
- you can manually attach the CSRF token in the header of each Axios call
- you can use the Axios xsrfHeaderName for each call
- you can use a default xsrfHeaderName (axios.defaults.xsrfHeaderName = "X-CSRFToken")
Here is how you can simply use the CSRF token with Axios without any further configuration:
import axios from 'axios';
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
Handling CSRF Tokens in React/Fetch
fetch(url, {
credentials: 'include',
method: 'POST',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
},
body: {}
})
}
Handling CSRF Using React/Redux
If you are using Redux to manage your application state you can use redux-csrf to handle CSRF token in Redux.
You can use by first installing it from npm with
npm install redux-csrf --save
Then you can use the setCsrfToken(token) API that set the CSRF token in the Redux store.
"X-CSRF-Token"or change your settings to not use CSRF (bad practice)