Missing CSRF token in Ionic - AngularJS FullStack application

Currently, I am working on a project with the backend on a MEAN stack that was initiated with the AngularJS Full-Stack generator and an Ionic app. Whenever I attempt to make a POST request for logging in from the Ionic app, the server responds with "CSRF token missing."

{"error":{"message":"CSRF token missing","stack":"Error: CSRF token missing\n    at checkCsrf (/Volumes/Data/Dev/carry/back/node_modules/lusca/lib/csrf.js:89:18)\n    at /Volumes/Data/Dev/carry/back/node_modules/lusca/index.js:48:21\n    at hsts (/Volumes/Data/Dev/carry/back/node_modules/lusca/lib/hsts.js:25:9)\n    at /Volumes/Data/Dev/carry/back/node_modules/lusca/index.js:48:21\n    at xframe (/Volumes/Data/Dev/carry/back/node_modules/lusca/lib/xframes.js:12:9)\n    at /Volumes/Data/Dev/carry/back/node_modules/lusca/index.js:48:21\n    at xssProtection (/Volumes/Data/Dev/carry/back/node_modules/lusca/lib/xssprotection.js:16:9)\n    at /Volumes/Data/Dev/carry/back/node_modules/lusca/index.js:48:21\n    at lusca (/Volumes/Data/Dev/carry/back/node_modules/lusca/index.js:53:9)\n    at Layer.handle [as handle_request] (/Volumes/Data/Dev/carry/back/node_modules/express/lib/router/layer.js:95:5)\n    at trim_prefix (/Volumes/Data/Dev/carry/back/node_modules/express/lib/router/index.js:312:13)\n    at /Volumes/Data/Dev/carry/back/node_modules/express/lib/router/index.js:280:7\n    at Function.process_params (/Volumes/Data/Dev/carry/back/node_modules/express/lib/router/index.js:330:12)\n    at next (/Volumes/Data/Dev/carry/back/node_modules/express/lib/router/index.js:271:10)\n    at /Volumes/Data/Dev/carry/back/node_modules/express-session/index.js:432:7\n    at /Volumes/Data/Dev/carry/back/node_modules/connect-mongo/lib/connect-mongo.js:305:11\n    at handleCallback (/Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)\n    at /Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1341:5\n    at handleCallback (/Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)\n    at /Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb/lib/cursor.js:670:5\n    at handleCallback (/Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:154:5)\n    at nextFunction (/Volumes/Data/Dev/carry/back/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:675:5)"}}

Despite sending the token and other data as shown in the request,

POST /auth/local HTTP/1.1
Host: 192.168.1.13:9000
Connection: keep-alive
Content-Length: 47
Accept: application/json, text/plain, */*
X-DevTools-Emulate-Network-Conditions-Client-Id: 552547EB-CA80-4AF8-8392-DDE2A9D833A4
Origin: file://
User-Agent: Mozilla/5.0 (Linux; Android 5.1.1; E5803 Build/32.0.A.4.11; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/48.0.2564.106 Mobile Safari/537.36
Content-Type: application/json;charset=UTF-8
Accept-Encoding: gzip, deflate
Accept-Language: en-US
Cookie: connect.sid=s%3AKpTipuTW9UAqmbx_X__fuDrfGxXiGRpF.%2FKf2gm3y%2F0VwBzUygchh7%2BVfi6PLoQZhOfI5T22XlxY; XSRF-TOKEN=iZvZ2wKb3VafJb9ZGqily3pBY3nGI9gVBQaww%3D
X-Requested-With: com.todomicilio.app

I have not made any modifications to the default configuration of the express server.

Answer №1

It appears that you have overlooked adding a CSRF token within the <form></form> used for making POST requests in your HTML code.

In your data, the CSRF token is only present in cookies. It is essential to also include the CSRF token in the form itself or as a special HTTP request header, depending on the implementation of protection mechanisms.

A brief explanation about Cross-Site Request Forgery (CSRF):

  1. How a CSRF attack can be executed:

Consider a scenario where there are two websites: "hacker.example" and "bank.example," which deals with financial transactions. If the bank.example website has a POST method /send-money to transfer funds between user accounts using a parameter like receiver-account and relies on cookies for user authorization.

If a user from the bank visits the hacker's website and unwittingly triggers a form submission to bank.example/send-money with the hacker's specified value for the receiver-account parameter, the browser will send this unauthorized POST request to the bank.example website along with valid cookies, thereby enabling the hacker to steal money from the unsuspecting user.

  1. Protecting against CSRF attacks (one possible solution):

To thwart CSRF attacks, employing two secret tokens—one stored in a cookie and another included in each post request made to the website—can serve as a protective measure. The server should validate these tokens during every post request initiated by a user.

  1. Why does this safeguard work?

With this setup, an attacker at hacker.example would require knowledge of the CSRF token to orchestrate a successful POST request. Obtaining this token poses significant challenges since they cannot access cookies from bank.example due to security protocols. Similarly, extracting the csrf token directly from the HTML code of bank.example's <form> is also impeded by CORS restrictions.

Answer №3

Although I am a bit late to respond, I wanted to share my solution as I encountered the same issue. Here is how I resolved it:

https://github.com/angular-fullstack/generator-angular-fullstack/pull/2613

"The issue arises when express.static() serves index.html, interrupting the middleware chain and preventing CRSF from being set on the / request. This can cause login failures for users without cookies.

I believe this solution may address issues #2224, #2511, #2611, and krakenjs/lusca#95."

This commit involves renaming _index.html to app.template.html, creating app.html as the output file instead. This change prevents express.static() from blocking the middleware chain by eliminating index.html. As a result, routes.js:sendFile is effectively called.

It is worth mentioning that I extensively experimented with webpack in search of alternative solutions, but this approach proved to be the most elegant one available."

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

React JS high-performance asynchronous computations

I'm currently facing a challenge with JavaScript while trying to perform complex calculations. I am using React together with Redux. Although making fetch or server requests using libraries like fetch or jQuery ajax works asynchronously as expected, ...

The Performance of My Device is Lagging When Executing CSS Transition Effects

I've been working on coding in HTML, but I've encountered an issue where my device seems to struggle with running CSS smoothly. You can take a look at the code I've written on CodePen. html { height: 100%; } body { background: linear ...

Capture video frames from a webcam using HTML and implement them in OPENCV with Python

While many may find it simple, I am facing a challenge in extracting video frames from HTML or JavaScript and utilizing them in my Python OPENCV project. I have a strong background in Python OPENCV and Deeplearning, but lack knowledge in HTML and JavaScr ...

Endless surfing just like Bing

I'm on the lookout for a library that can enable continuous scrolling in jQuery and/or JSP, similar to the functionality seen in Bing Images. Specifically, I want the feature where only the results within the visible area are loaded when users scroll ...

Dealing with a redis connection issue in an express application

I have a database in Express that is able to connect to multiple Redis servers by receiving the connection IP address from a client. Everything works well if the Redis database exists. The issue I'm encountering is when the IP address does not exist, ...

Angular Modal Service Unit Test Template for $uibModal

My service has a simple show() function that basically calls $uibModal with some configuration and returns the modal instance function customModalService($uibModal) { return { show(message) { return $uibModal.open({ bindToController: t ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

Jasmine for testing HTTP POST method in a unit test case

I am struggling to write a unit test case for the post method in an Angular service. I keep getting an error saying $http is undefined. Below you can see my code. Can anyone please help me figure out what I am missing? I am adding the module using a separ ...

Tips for choosing a specific cell in a table

I currently have a total of 14 cells that have been generated. Is there a way for me to individually select and manipulate a specific cell out of the 14? I am looking to make only one cell unique, while leaving the rest to be displayed as they are in the ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Creating a Shopping Cart using Laravel and Angular

My current application features a shopping cart that works well for me, but my colleague finds it to be too "slow". I have been brainstorming ways to improve its efficiency and speed. This is the process of how my page currently loads: The Product/Ticke ...

How to hide an image in the React carousel display

I am having an issue with my Carousel, specifically with the image not being displayed even though I have set up the data in a const called items. Here is how my const looks: var items = [ { url:'../../assets/img/hors1.jpg', ...

Every time I switch to a new Vue.js route, I find myself inexplicably redirected to the bottom of the page, leaving me scratching my head in confusion

I'm really struggling to understand why this issue is happening because there doesn't seem to be any code that would interfere with the scrolling. Every time I click on the link, it immediately takes me to the bottom of the view. I'm not sur ...

Clicking on buttons in the header does not lead to the intended section when scrolling

I have just completed a website project for a Udemy course, following all the instructions provided. However, I am facing an issue with the functionality of two buttons on my site. I want these buttons to scroll to specific sections when clicked. The "I&ap ...

Does __ only function with curried functions as intended? What is the reason for it working in this case?

I'm trying to figure out the reason behind the successful usage of __ in this particular code snippet : function editAddress (id, addressId, model) { return BusinessService .getById(id) .then(unless( () => checkUrlValue(add ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

Tips for implementing a smooth fade-in effect while rotating URLs within an iFrame

As I cycle through a list of URLs, I am displaying each one in an iFrame for a specific amount of time based on the corresponding value in the durations array. (function step(){ $j('.marquee').attr('src',urls[i].innerHTML); setTime ...

Searching for objects with distinct hash codes using an AngularJS filter

My title may be long, but I want to explain something: I am using a service called: divisionService This service has a function that returns a list of all Divisions in my system. I use this list to populate a select: <select class="form-control ...

When using findOneAndUpdate to modify specific elements within an array, the Mongoose library is failing to update the booleanValue field in the array

Updating a boolean value in an object within an array in a mongo document using mongoose is proving to be tricky. app.post("/api/post/:chorecomplete", function(req, res){ Parent.findOneAndUpdate({parentFirstName: req.body.parentFirstName, parentLastN ...