Retrieve, establish cookies, and guard against CSRF attacks

Having some difficulty with CSRF in my application while using Isomorphic fetch.

The backend sends a CSRF-TOKEN in the set-cookies property:

https://i.sstatic.net/duODj.png

There is advice against directly accessing these cookies in code, so I attempted utilizing the credentials property in the fetch request:

const headers = new Headers({
            'Content-Type': 'x-www-form-urlencoded'
        });
        return this.fetcher(url, {
            method: 'POST',
            headers,
            credentials: 'include',
            body: JSON.stringify({
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e131f17123e131f171252180c">[email protected]</a>',
                password: 'password'
            })
        });

This allows me to send the CSRF cookie back to the server for a different request:

https://i.sstatic.net/OcotU.png

Encountering an Issue:

The backend requires an x-csrf-token header which cannot be set in the POST request.

Solution Required:

How can I transfer the value of set-cookies: CSRF-TOKEN into the next request's x-csrf-token header?

Answer №1

It appears that in the given situation, you need to extract information from the CSRF-TOKEN cookie. If not, it would be labeled as HttpOnly like JSESSIONID. The latter signifies that it cannot be accessed through the web page but merely sent back to the server automatically.

Typically, there is nothing erroneous with retrieving a CSRF token from cookies. You may find this insightful discussion helpful: Why is it common to put CSRF prevention tokens in cookies?

To read your cookie (which is not HttpOnly, of course), you can utilize the following code:

function getCookie(name) {
  if (!document.cookie) {
    return null;
  }

  const xsrfCookies = document.cookie.split(';')
    .map(c => c.trim())
    .filter(c => c.startsWith(name + '='));

  if (xsrfCookies.length === 0) {
    return null;
  }
  return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}

Therefore, when making a fetch call, it should resemble this:

const csrfToken = getCookie('CSRF-TOKEN');
      
const headers = new Headers({
        'Content-Type': 'x-www-form-urlencoded',
        'X-CSRF-TOKEN': csrfToken
    });
    return this.fetcher(url, {
        method: 'POST',
        headers,
        credentials: 'include',
        body: JSON.stringify({
            email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d68756c607d6168236e6260">[email protected]</a>',
            password: 'password'
        })
    });

Answer №2

The name of the header can vary depending on your server configuration. For instance, in a Django setup, you would set up CSRF token using fetch as shown below:

  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8',
    'X-CSRFToken': get_token
  },

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

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Python3 was installed, but the version couldn't be located

After trying to install a module on NPM, I encountered this error despite already having Python 3 installed and my ENV path set correctly. I attempted to install the NPM module, but it did not work as expected. ...

Changing TypeScript Enum from String to Number in Angular

Does anyone know how to convert a Typescript enum value to a number for display in a dropdown but passing the numeric value on submit? Here is how the enum is currently set up: I am currently able to output the string key of the object when it is emitted ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...

Ensure that text input is restricted from containing any HTML or script tags when utilizing the Web API within an HTML page

On a html page, there are two text boxes provided for entering Employee Name and Employee Age, along with a Save button. Clicking this button triggers the Web API method called SaveEmployeeData to save the data. This Web API is hosted on an asp.net website ...

Numerous classifications and tags available for c3-angular-directive-c3 charts

I have a project requirement to create a stacked bar chart that should look like the image below: https://i.sstatic.net/MBwXy.png Currently, I am utilizing the c3-angular-directive library along with c3.js for chart creation. The challenge lies in dealin ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Directives for Nested Elements in AngularJS

I am currently working on creating two custom elements: <accordion> and <accordion-group-active>. .directive('accordion', function () { return { restrict: 'E', replace: true, transclude: true, ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

Error encountered while trying to authenticate user through post request

I have written a post route request function below to handle user login. However, I keep encountering 401 unauthorized errors when making the request. Can anyone suggest any modifications or refactorings that could potentially fix this issue? Thank you i ...

Increase the value of a property within an array of objects based on certain conditions

My task involves incrementing the rank value by one until the name property changes. I am utilizing the page and rank properties to track when this change occurs. In addition, I want to increment it once whenever the type is not equal to none, and then re ...

Using AngularJS in conjunction with other scripts

I am currently working on an application and now I have the task of implementing a dynamic menu using AngularJS. This requires me to modify variables in the AngularJS application from my existing code. Here is the example I am experimenting with: <scr ...

Looking to display the "loading....." message on a PHP page?

I am working on a PHP webpage where I need to implement the following features: 1. Upon clicking "Say Thanks", it should change to "Done!". 2. Simultaneously, I would like to trigger an action in the indexController. 3. While this action is happening, I wa ...

Extract the image URL from the href attribute using Xpath

My goal is to extract all images enclosed in href attributes from the given code snippet <div class="jcarousel product-imagethumb-alt" data-jcarousel="true"> <ul> <li> <a href="https://domain/imagefull.jpg" onclick="return false;" cla ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...

Encountering issue with 'mongodb-connection-string-url'

As a beginner, I am struggling to understand the error message. When I try to run the app.js file, I receive the following log message. I read that I need to upgrade my MongoDB, but since I am using Windows 7, this seems impossible. PS G:\AWebDev&bsol ...

Stopping a jQuery AJAX request after receiving another response

I am facing a problem and I need some creative solutions :) Currently, I have two $.ajax calls in my code. The first call is asynchronous and takes a long time to respond (approximately 1 minute). On the other hand, the second call is synchronous (with as ...