Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function, I am facing issues when trying to send the csrf value to the server using Axios ajax framework.

Even after adding the @ensure_csrf_cookie decorator to views.py, I continue to encounter a 403 error. While using the @csrf_exempt decorator resolves the issue, I prefer to stick to using csrf for security purposes.

I am currently working with Django Version 3.0.8 in a venv environment.

A snippet from csrftoken.js:

import React from "react";
function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
var csrftoken = getCookie("csrftoken");

const CSRFToken = () => {
  return <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />;
};
export default CSRFToken;

Snippet from App.js:

...
import axios from "axios";
import CSRFToken from "./csrftoken";
...
sendPost() {
var jsonPost = {
      csrfmiddlewaretoken: document.getElementsByTagName("input")[
        "csrfmiddlewaretoken"
      ].value,
      transmitter: "This is houston Do you hear me Copy ",
    };
   axios({
      method: "post",
      url: "/api/sendpost/",
      data: jsonPost,
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }
...
 render() {
    return (
      <ul>
        <CSRFToken />
        {this.state.data.map((contact) => {
          return (
            <div>
              <li key={contact.id}>
                {contact.name} - {contact.email}
              </li>
              <button onClick={() => this.sendPost()}>
                Send A Post Message
              </button>
            </div>
          );
        })}
      </ul>
    );
  }

Snippet from leads app's views.py:

from django.views.decorators.csrf import csrf_exempt,ensure_csrf_cookie
from django.http import JsonResponse
#@csrf_exempt
@ensure_csrf_cookie
def receivePost(request):
    print(request.POST)
    data = {
        "receiver":"Received Houston"
    }
    return JsonResponse(data)

Snippet from settings.py:

...
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.authentication.TokenAuthentication',
    ),
}
...

Snippet from urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('api/lead/', views.LeadListCreate.as_view() ),
    path('api/sendpost/', views.receivePost ),
]

Edit: Despite enabling @csrf_exempt on views.py, the print(request.POST) returns an empty Querydict {}

Answer №1

Ensuring the security of your backend is crucial when making a post request to prevent any unauthorized tampering of data by hackers who may intercept the communication between client and server. This is where CSRF tokens come into play, encrypting each request with a unique string containing symbols, letters, and numbers.

Now that you understand the purpose of CSRF tokens, it's important to include this token in your requests so that the backend can verify its authenticity against the stored token on the server.

Your mistake lies in the axios call where you neglected to add the CSRF token to the POST request.

The correct code solution is as follows:

import Cookies from 'js-cookie'
axios.post(
'/api/sendpost/',data, {headers:{'X-CSRFToken':Cookies.get('csrftoken')}})
.then((res)=>{
  console.log(res)
})
.catch((e)=>{console.log(e)})

It's worth noting that I am utilizing the js-cookie module for managing cookies.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for handling 429 errors while using axios in a react native application

My React Native app is connected to a MongoDB database using Express and Node.js, with Axios handling client-server communication. The app frequently exchanges data with the database, sometimes up to 4 requests per second when in use. While everything wor ...

Is it feasible to execute rendering while performing a Drag and Drop operation in ReactJs?

Can ReactJS handle rendering during a Drag/Drop operation? I'm looking to create a month view calendar in ReactJS where, when dragging a multi-day event backwards and forwards, all other day events on the calendar also move to show the effect before ...

Tips for effectively utilizing Vuex to manage items within a Vuetify data table

I am currently sending an API request to retrieve an array of objects that has the following structure: returnedItems [ { name: 'Adam', age: '30', interest: 'Sports' }, ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Exploring component method variables with Jest testing

Imagine a scenario where there is a class component with the following structure: export class Math extends React.Component { ... someComponentMethod = numb => { const sample = numb * 10 ... const result = numb -5 ...

Performing a `contains` operation with JQuery on this variable or object

Help! I'm completely confused about this problem. First, I am trying to use jQuery to select an li object and then check if a certain text exists within it using the "contains" function. However, for some reason, the line with the "contains" function ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

An efficient method for importing 2-dimensional data in Python with minimal memory usage

When running Python scripts to analyze data, I encountered a surprising issue with the amount of RAM being used: The script reads two columns of integers from a file using the following method: import numpy as N from sys import argv infile = argv[1] data ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

HTML control for adjusting the pan and tilt of a device

I'm looking to develop an interactive input where users can drag a dot within a box and see the 2D coordinates of that dot displayed. The goal is to use this feature to control pan and tilt values. A similar functionality from another application is s ...

Issue: "Invalid CSRF token. Request cancelled." encountered while utilizing jQuery JSON with Django

I am working on a project where I need to retrieve JSON data and store it in a database using Django. However, when I try to post the JSON data, I encounter the following error message: Forbidden (403) CSRF verification failed. Request aborted. Here is ...

Building a dropdown feature for rows in a table using ReactJS

I am utilizing a Material UI Table, and within one of the columns I have a SelectField component that displays a dropdown with a few selectable items. Here is a snippet of the code: <TableBody displayRowCheckbox={this.state.showCheckboxes} ...

What is the reason behind my styled component only displaying the final state in its className logs?

Here is my implementation using styled components with the version "@types/styled-components": "^5.1.26" and I'll provide you with an example of my code. // index.tsx import React, { useEffect, useState } from 'react'; i ...

Ways to verify the authenticity of a JWT token

I recently came across a tutorial on creating user authentication with Vue.js and Lumen. The tutorial utilizes the tymon/jwt-auth library to handle authentication. So far, everything is working smoothly. The API manages all my data and provides a token to ...

Retrieving script data from a webpage

I found a link that I want to extract content from, here is the link: https://www.whatever.com/getDescModuleAjax.htm?productId=32663684002&t=1478698394335 However, when I try to open it using Selenium, it doesn't work. It opens as plain text wit ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Developing a side panel for navigation

My goal is to create a sidebar that shifts to the right from the left side and makes space on the page when the hamburger menu is pressed. I have made progress in achieving this, but I am encountering difficulties with the animation. const btnToggleSide ...

Unable to retrieve event data and integrate it into HTML using jQuery

Just starting out with leaflet and JavaScript, jQuery. I've got an index.html page displaying a map, and want to show the coordinates of the mouse pointer underneath the map when it moves. To achieve this, I have a div element with the id "coordinat ...