Django, X-CSRFToken is set incorrectly in request header
basically, i got this to actually send a csrf token to the frontend and set it there in cookie section in application tab in dev window in the browser:
@method_decorator(ensure_csrf_cookie)
def get(self, request, format=None):
return JsonResponse({'csrftoken':get_token(request)})
in react side:
useEffect(()=>{
axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{
console.log(res.data)
Cookies.set('csrftoken',res.data.csrftoken)
})
},[])
let handleSubmit = (e) => {
e.preventDefault();
axios
.post("http://127.0.0.1:8000/signup/", signup, {
withCredentials: true,
headers: { "X-CSRFToken": Cookies.get("csrftoken") },
})
.then((res) => {
setDisabled(true)
setIsUp(true)
setTimeout(()=>{setIsUp(false)
redirect('/')},3000)
})
.catch((e) => {
console.log(e.response.data)
let err = e.response.data
setError(err);
});
};
on my local machine (on the local hosts):
as you can see both Cookie
and X-CSRFToken
are matching in request header, however, in production:
and the weirder part is that in request header the name of the key in local host is Cookie
, but in production it is cookie
(c and C difference)
and of course I get an error when i make a post request in production server:
<p>CSRF verification failed. Request aborted.</p>
</div>
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre> CSRF token from the 'X-Csrftoken' HTTP header incorrect.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a href="https://docs.djangoproject.com/en/4.0/ref/csrf/">Django’s
help me understand the problem, and KINDLY help me understand the correct way to actually retrieve csrf token in case it was missing from application
tab in dev console in the browser
I think you are puzzling things, CSRF is always there by default, which means you do not require to generate a csrf-token
.
For Axios
just use it like this:
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
axios.post("/url",{
key: value
})
.then(function (response) {
//your code....
})
.catch(function (error) {
//error handling
});