Issue
I’m building an app with a React frontend and Django backend. But the issue is I need csrftoken. How do I generate csrftoken in Django when I make an APi call to the endpoint. I have searched but can’t find the solution. I have tried using csrf_exempt which works but I know this is not secure, please help. Thanks
Solution
In a typical Django application, CSRF tokens are automatically included in the HTML when rendered by Django. However, when making API calls from a React frontend to a Django backend, you need to manually include the CSRF token in your requests.
To achieve this, you can create a function to retrieve the CSRF token from cookies. Here's an example:
const getCookie = (name) => {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
Now, before making a request, you can generate the CSRF token and include it in the request headers as follows:
const csrfToken = getCookie('csrftoken');
const url = "endpoint_url";
const payload = {};
const headers = {
"X-CSRFToken": csrfToken,
"Content-Type": "application/json",
Accept: "application/json",
};
const { data } = await axios.post(URL, payload, {
headers: headers,
});
This ensures that the CSRF token is properly included in your Axios request headers, allowing your Django backend to authenticate and process the request securely. Adjust the function and variable names as needed based on your application's specific setup.
Answered By - Temi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.