Matching the cookie and header in express.js CSURF results in a 403 error code

My express server setup is quite simple:

  app.use(bodyParser.json());
  app.use(cookieParser());
  app.use(csurf({ cookie: true }));
  // routes
  app.use(Routes imported from another file);

Currently, the client side consists of a basic form in react. I'm loading some initial data before the react app loads and setting the csrf cookie there.

I have created a straightforward function for parsing the csrf cookie on the client side. Since I am proxying the express server in create-react-app, I cannot just set a meta tag in the header.


const csrfToken = () => {
  const cookies = decodeURIComponent(document.cookie).split(';');
  const token = cookies.find(cookie => cookie.includes('_csrf'));

  if (token) {
    return token.split('=')[1]
  }
}

When sending data along with the token, I am using fetch

const response = await fetch(url, {
      credentials: 'include',
      method: 'POST',
      headers: {
        'Connection': 'keep-alive',
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken()
      },
      body: JSON.stringify({ ...body })
    });

Despite trying to troubleshoot by commenting out the csurf line and verifying that all necessary elements are present in the request, I am still receiving a 403 error. It seems like everything is correct, but something must be missing. I'm not sure what could be causing this issue, especially since my setup closely resembles others found online.

Answer №1

When it comes to handling CSRF protection, there are specific steps you need to follow in order to securely generate and verify the necessary data. Simply reading the content of the _csrf cookie and sending it back inside an X-CSRF-Token header won't suffice.

To ensure proper validation, the csurf middleware within Express must be set up correctly. This can be achieved by using the following code snippet:

app.use(csurf({ cookie: true }));
. By doing this, the middleware will take care of generating the _csrf cookie and sending it to the client. As a developer, your role is to:

  1. Generate the second piece of CSRF data on the server.
  2. Attach this second piece of data to the response sent to a client. This ensures that the client receives both the _csrf cookie and the additional data.
  3. Verify that the incoming request from the client contains both the _csrf cookie and the second piece of data, which should be placed in one of the predefined locations (such as the 'X-CSRF-Token' header).

For further insights, refer to the detailed explanation provided in this answer.

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

How can I securely store passwords for web scraping with Puppeteer to ensure maximum safety?

Looking for advice on scraping a website that requires login. The current code saves username and password in a config JSON file, which poses a security risk if the file is accessed by unauthorized individuals. Is there a more secure method, such as encr ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

What is the process by which Reactjs obtains data from firebase function triggers in a specific manner?

I am currently utilizing express to develop my firebase functions, and while I have a good grasp on creating standard callable functions, I am struggling with the implementation of trigger functions for background operations (such as onCreate, onDelete, on ...

Incorrect NPM version is installed along with Node

Hello everyone, I had previously asked this question without any response. I'm reposting in hopes of finally receiving some much-needed answers. Currently, I am following a tutorial on NodeJS. The tutorial instructs me to "install this version of npm ...

Guide to Setting User Permissions with CheckboxList in MERN Stack

I have been working on implementing user permissions in MERN using a checkbox list. Initially, I tried manually granting access by using an if and else statement to give fixed authorization based on the user's role. Here's how it looks: {user.ro ...

The current Webpack configuration for production fails to account for importing CSS files

I am struggling to figure out how to properly load a static site that is not located in the root folder: let HWPTest = new HtmlWebpackPlugin({ template: __dirname + "/src/artists/test.html", filename: 'artists/test.html', favicon: &apos ...

Examining the ExpressJS endpoint using Jest

Currently, I am attempting to test an endpoint in my express application using Jest. In order to improve the speed of testing, I have decided to switch from Mocha to Jest. However, I have encountered an issue where my Jest test does not close properly. I ...

Can you explain the benefits of using Karken.js to enhance the security and scalability of Node.js applications?

After reviewing multiple presentations and slides discussing how PayPal utilizes Karken.js within its Node.js Stack for enhanced security, it seems that it also integrates well with dust.js. However, the pressing inquiry remains: is this simply a tool to ...

Specialized system environment variables, specifically predefined for Node and NPM

Is it possible to pre-define special-purpose variables for Node? I've noticed that Windows system environment variables such as %PATH% and %OS% are accessible in Node. You can also create your own custom variables, all of which can be accessed using ...

Creating custom paths by using Express Route Parameters may lead to the generation of

Currently, I am in the process of developing a to-do list application and facing some challenges while incorporating custom routes utilizing 'Express Route Parameters'. Everything was functioning smoothly until I attempted to implement these cust ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Error: Package [email protected] could not be located

While attempting to launch my project, I encountered an unexpected error message. npm ERR! 404 Not Found: [email protected] ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

What is the proper way to display the complete result of aggregating each outcome from the previous iteration within two nested queries in an array using NodeJS and Mongoose?

As a newcomer to both Stackoverflow and NodeJS/Mongoose, I apologize if I make any mistakes or break any rules. Thank you in advance. I'm looking for a function that can return all nearby products based on my current location, which is provided by th ...

What is the best way to save a file in each directory that has been accessed?

I am working with a folder structure that contains multiple directories and files. My goal is to create a file in each directory to keep track of which files have been read. This created file will then be used as a condition to decide whether to skip or re ...

What steps should I take to fix the issue of npm audit showing ENOAUDIT error: The registry specified in your configurations does not allow

I recently encountered an issue with my project and I'm not sure what caused it. The only changes I made were adding some extra dependencies. I use the default https://registry.npmjs.org/. Below is a snippet from the log file showing the error message ...

deploying both my backend and frontend on firebase platform

My test project is created using React JS for the frontend and Node JS for the backend, organized in their respective folders: -frontend (folder) ---- React JS -backend (folder) ---- Express JS It works perfectly locally, but now I want to publish it ...

The function batchWriteItem() has been known to produce unpredictable outcomes

Currently in my Node.js project, I am attempting to write records to a DynamoDB table using the batchWriteItem() method. When I call the insertTransactionDetails() function for the first time, I send 9 records to be inserted. On the second call to the sam ...

Accessing a particular level within a JSON object in Node.js

I'm dealing with a two level JSON structure {"Policy": { "Channel": "online", "Credit Score": "20000", "Car": [{ "Age": "28", ...

Error Code 1002 on WebSocket Closing

I have developed an application that utilizes web sockets to establish communication between the server and client. In the event that the client's version is outdated (too old) and cannot interpret or handle messages correctly, I would like to address ...