I am trying to send the csrf token i genenrated
here is the csrftoken generation
const [cr , setCR] = useState('')
const getcsrf = async () => {
await fetch('http://localhost:8000/auth/gettoken')
.then( async res => await res.json()).then(data =>{
setCR( data.crsftoken)
console.log(cr)
})
}
useEffect( () => {
getcsrf()
},[] )
after i have obtained the token i try to send it using fetch
const handlelogin = async () => {
if(cr !== ''){
console.log(cr)
await fetch('http://localhost:8000/auth/login',
{method : "POST",
credentials: "include" ,
headers: {
"Content-Type": "application/json",
"X-CSRFToken" : cr
},
body : {
"username" : username,
"password" : password
}
}
).catch(err => console.log(err))}else{console.log('cr is null')}
}
the csrf token is generated i can see it when i console.logged it but the fetch brings back a 403 forbidden error
Forbidden (CSRF token from the 'X-Csrftoken' HTTP header incorrect.): /auth/login
[09/Nov/2023 05:49:59] "POST /auth/login HTTP/1.1" 403 2553
i am expecting it to post to the url i gave it. what is wrong with it?
2
Answers
CSRF Middleware token is generated automatically with each request so the value you sent has a probability of not matching subsequent requests as there is a GET request in the middle.
If you want to do CSRF, it is better to manage it manually not through CSRF Middleware and maybe Django Rest framework has a fix for this.
CSRF is easy.
In your Django template, include {% csrf_token %} within the form.
Retrieve the CSRF token in your React component: for example const csrfToken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
Configure Django to accept the CSRF token from the header: for example In settings.py files you have token (CSRF_HEADER_NAME = ‘HTTP_X_CSRFTOKEN’).
Note -> Ensure your Django view allows POST requests from your React frontend.