Passport.js securely manages cross-origin resource sharing (CORS) domain sessions

I've organized my application into a 3-tier structure. The server is powered by node.js and the front end is built with Angular. For user login and authentication, I'm using passport. However, I've encountered an issue where my passport login cannot maintain a cross-domain session on the front end.

The server is running on localhost:3000 while the front end app is on localhost:9000.

I attempted to configure CORS requests in Express by setting options as:

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    if ('OPTIONS' == req.method) {
        res.send(200);
    } else {
        next();
    }
});

I also tried using the CORS module in Node.js, but nothing seems to be working for me. Any help or suggestions would be greatly appreciated.

Answer №1

To enhance security and prevent cross-domain attacks, utilizing csurf is essential.

Whenever a page is requested, such as a login page, the server sends a token along with the request. This token must be set in a hidden field within the form. When the form is submitted to the server, the token is verified for authenticity.

Get more information about csurf on GitHub

Learn how to implement CSRF protection with Express 4

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

Having trouble installing firebase using npm

Currently, I am utilizing React (if that's relevant). While researching on Google, the common solution I found was to clear the npm cache: npm cache clean --force However, this method didn't resolve the issue. I also went ahead and deleted the ...

Unable to submit form in Nextjs using react-bootstrap

Instructions To create a registration form, follow these steps: Fill out the form on the register page and then click submit. The react-bootstrap button will trigger the handleSubmit() function using onSubmit={}. Expected vs Actual Outcome I attempted va ...

Having trouble with Firebase admin in your Next.js/Stripe webhook integration?

I've encountered an issue when using the stripe webhook in Next.js. Every time I attempt to set it up, I receive the following error: unable to detect a project id in this environment I initially tried setting it up in the app router and then trans ...

When using Node.js to redirect a request, the HTTP status code returned is 304

Implement session as an Interceptor in the following code snippet: app.use(function (req, res, next) { var url = req.originalUrl; var arr =[]; arr = req.originalUrl.split('/'); if (arr[1] != "login" && !re ...

Rearrange lists by dragging and dropping them according to specific criteria

In my AngularJS project, I am utilizing the angular-drag-and-drop-lists library from here to create two lists with the following functionalities: Dragging items from list A to list B Dragging items from list B to list A Reordering items in list A Reorder ...

Angular version 1.6 with ES6, no errors in the application

Can you help me understand this? Note: I am using ui-router, and I suspect that is the issue. $stateProvider .state('login',{ url:'/', /*controller:'loginController',*/ controller: function(){aler ...

AngularJS UI-Grid not displaying JSON data

Just started learning AngularJS and everything was going smoothly until I hit a roadblock... I have been struggling to display the JSON data returned from my REST service call. While hard-coding a data array in my controller works fine, displaying the act ...

Error in Node JS: Unable to retrieve data with search query

I am in the process of creating a simple twitter sentiment analysis application using node, express, twit, and sentiment. The idea is to allow the user to input a search term, and then receive a sentiment analysis as long as the stream is active. But, wh ...

Utilizing the Teams web app within my customized electron application

I've been developing an electron app and am trying to integrate the MS Teams web app into it. I've successfully displayed MS Word, MS Powerpoint, and other apps using window.loadURL(''), but I'm experiencing issues with MS Teams. D ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

The expression "const io = require('socket.io')" cannot be invoked as a function

This is my index.js file running on the server side const express = require('express'); const app = express(); const server = require('http').createServer(app); const PORT = process.env.PORT || 5000; const router = require('./rou ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

NodeJs error: 'messages is not a function'

Getting Error: messages is not a function Why does != messages('message',locals) show an error? Even though it seems correct. Please assist me in identifying the error. Thank you! app.js app.use(require('connect-flash')()); app.us ...

When the button is clicked, the ng-click event will trigger the addClass function, but only on the second click

My bootstrap alert has this structure: <div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-if="itemExistsAlert"> <button type="button" class="close" data-dismiss="alert">&times;</button> <p>{{alertM ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

Can you explain the working mechanism behind mongoose.connect(connectionSring)?

Having a background in Python where I connected to databases and executed SQL without an ORM using the cx_Oracle library, my approach was similar: >>> conn = cx_Oracle.connect(connectionString) >>> curs = conn.cursor() >>> _ = c ...

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

Is it possible to execute an npm command within a docker container?

I am facing an issue while attempting to run my Angular application in development mode within a Docker container. When I use docker-compose build, everything works fine, but when I try to start the container, I encounter the following error: ERROR: for ...

The issue with `findOneAndUpdate` not saving a new item persists (Mongoose, Node.js)

Looking to store objects in a database using Mongoose library. Specifically, I receive search queries and save them to the database while keeping track of the count of unique entries. Below is my schema: const entrySchema = mongoose.Schema({ searchWo ...