The anonymous function in the Google strategy is not being executed

I am currently working on implementing Passport to allow users to log in to my website using their Google accounts. I am utilizing yarn along with the following relevant packages: [email protected], and passport-google-oauth20@^1.0.0. The issue I am facing seems to be related to the callback function defined in the GoogleStrategy not getting executed, leading to errors as the server tries to load a non-existent page.

When I start the server using nodemon and pass the Google client ID and secret as process variables which are then used by the GoogleStrategy (I have verified this through console logs), I navigate to the root page through the browser and click on the login anchor that directs me to /auth/google. At this point, the Google login screen appears with options to choose an account for login. After selecting my account, the server receives a GET request to

/auth/google/callback?code=4/(a long string of characters)
resulting in a 500 error. Following this, all files referenced in the pug file of the root page are requested via GET, prefixed with auth/google except for the stylesheet.

Here is an example output of these requests:

GET /auth/google 302 1.893 ms - 0
GET /auth/google/callback?code=4/(long string of text) 500 178.246 ms - 3087
GET /auth/google/node_modules/jquery/dist/jquery.js 404 38.048 ms - 3087
GET /auth/google/node_modules/bootstrap/dist/css/bootstrap.css 404 65.666 ms - 3087
GET /auth/google/node_modules/angular-material/angular-material.css 404 89.565 ms - 3087
GET /auth/google/node_modules/angular/angular.js 404 115.541 ms - 3087
GET /auth/google/node_modules/angular-animate/angular-animate.js 404 141.761 ms - 3087
GET /auth/google/node_modules/angular-messages/angular-messages.js 404 161.489 ms - 3087
GET /auth/google/node_modules/angular-material/angular-material.js 404 23.809 ms - 3087
GET /auth/google/node_modules/angular-aria/angular-aria.js 404 43.268 ms - 3087
GET /auth/google/apps/angular_app.js 404 62.520 ms - 3087
GET /stylesheets/style.css 304 86.279 ms - -

At this stage, the page seems to only display elements from its main pug file and the CSS file; functionalities like ng-repeats or ng-includes do not work. The URL in the browser at this point is

http://(my domain)/auth/google/callback?code=4/(a long string of characters)

The code snippet below shows the relevant portion in the express file for the root page:

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;

console.log('google client id: ' + process.env.GOOGLE_CLIENT_ID);
console.log('google client secret: ' + process.env.GOOGLE_CLIENT_SECRET);
router.use(passport.initialize());

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: 'http://(my domain)/auth/google/callback'
},
function(accessToken, refreshToken, profile, done) {
  console.log('start of callback');
  return done(null, profile);
}));

app.use(passport.initialize());

router.get('/auth/google', passport.authenticate('google', {scope: ['profile']} ));
router.get('/auth/google/callback', passport.authenticate('google', {
  failureRedirect: '/',
  function(req, res, next) {
    res.redirect('/');
  }
}));

router.get('/logout', function(req, res) {
  console.log('logged out');
  req.logout();
  res.redirect('/');
});

module.exports = router;

The line

console.log('start of callback');
does not seem to execute at any point during the flow mentioned in the second paragraph. However, the line console.log('logged out'); executes when clicking the logout anchor followed by the redirect function.

Below are some resources I have consulted to troubleshoot why the strategy fails to run the anonymous callback function:

  • Passport-Google-OAuth Callback Not working
  • Custom Callback never called when Google Auth on passportjs
  • Passport Callback isn't called Google API
  • how to redirect to original page after successful authentication using passport-google-oauth
  • Passport-Google-OAuth Callback Not working when used in Web Service
  • Google-oauth2 passport not working
  • Passport Authenticate doesn't redirect
  • https://github.com/mstade/passport-google-oauth2

Answer №1

In my quest to solve the issue, I decided to experiment with adding session functionality to determine if Passport and Google oauth 2.0 relied on it. It turned out that they did indeed require basic session functionality in order for the callback function to be triggered successfully. Although there wasn't explicit documentation indicating the necessity of sessions, a thorough review of the "read me" page on the GitHub repository linked in my initial question revealed a subtle hint suggesting that sessions are essential for Google oauth 2.0.

I also discovered that both the sign-in button and callbackURL must share the same URL to prevent the creation of two cookies, which could potentially disrupt your session.

Therefore, based on my findings, it seems that sessions are an integral part of utilizing Google oauth 2.0.

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

jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for ...

Warning: data and salt parameters are necessary, please provide them

Issue: I am encountering an error with registering a new user, specifically when using Postman. I'm not sure why this error is occurring only in Postman. Additionally, I am facing proxy problems where requests cannot be proxied from localhost:3000 to ...

How come my invocation of (mobx) extendObservable isn't causing a re-render?

Can't figure out why the render isn't triggering after running addSimpleProperty in this code. Been staring at it for a while now and think it might have something to do with extendObservable. const {observable, action, extendObservable} = mobx; ...

Remove any errors as soon as the input field becomes valid

My current setup involves AngularJS with node.js. To handle errors, I have devised the following strategy: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Eff ...

Issue detected: data exceeds limits (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) within next-js and ethereum

While working on my Ethereum and Next.js project, I encountered an error during the initialization of the project: Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) at Logger.makeError (/home/Documents/projects/eth ...

Unfortunate Outcome: CSS Request Results in 404 Error

Recently, I made a transition from having a single-page website to using an express server for my website. During this process, I had to modify the file paths. However, I am encountering difficulties in loading my css and js files. Upon inspecting the dev ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...

Is there a way to fetch a random record from a MongoDb collection and exhibit all the fields of that haphazardly chosen document in HTML?

In my current project, I am fetching a random document from a MongoDB Collection and attempting to showcase all the fields of that document in HTML. Although I can successfully retrieve a random document, the issue arises when trying to display its fields ...

Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window? You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/ I would like the image to be already scaled vertic ...

Express session not persisting properly after deployment on both Heroku and Netlify platforms

I recently deployed my React frontend to Netlify and my Express backend to Heroku, both using session management. While the session functionality works perfectly locally, it does not seem to work after deployment. Upon checking the database, I can see th ...

Debian on Node Express always serves index.html by default

I am currently facing an issue with my node express server. It works correctly on a Windows system, but when running on Debian, it always returns index.html. Whenever I try to access localhost:port/ in the browser, it displays index.html. The problem is t ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

What is the best way to retrieve a response from a modal dialog using jQuery?

Is there a way to utilize an add-in such as simple-modal or the dialog add-in in the UI kit to achieve AJAX interaction with the server? I am looking for a solution that allows the modal to communicate with the server and return the result back to the ca ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

Is it possible to customize the CSS styles of a jQuery UI modal dialog box?

Having trouble with my CSS styles not applying to a dialog modal added to my website using jQuery UI, even when using '!important'. I suspect that the predefined jQuery or UI CSS styles from a CDN link are preventing me from overriding them. The ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

What is the process for changing a DynamoDB table from PROVISIONED to PAY_PER_REQUEST using Node.js?

Currently, I have a DDB table set up with BillingMode: PROVISIONED and ProvisionedThroughput:{...}. My goal is to switch it to BillingMode: PAY_PER_REQUEST, but every time I attempt this change, I encounter the following error: TypeError: Cannot read prop ...

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...