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

a comprehensive guide on integrating sinon js with Express js for effective unit testing

Hello, I am interested in performing unit testing on my express js code and I am looking to mock data for this purpose. After researching various websites and blogs, I came across this library. However, I am uncertain about how to utilize this library for ...

Hey there, could you please set up the DateTimePicker in my expo project using React Native?

Hey everyone, I'm currently trying to set up DateTimePicker but encountered an error. Here's the issue: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: undefined@undefined npm ERR! Fou ...

Enhancing this testimonial slider with captivating animations

I have designed a testimonial slider with CSS3 and now I am looking to enhance it by adding some animation using Jquery. However, I am not sure how to integrate Jquery with this slider or which plugins would work best for this purpose. Can anyone provide g ...

Tips on creating a transition in React to showcase fresh HTML content depending on the recent state changes

I am completely new to React and recently completed a project called Random Quote Machine. The main objective was to have a method triggered inside React when the user clicks a button, changing the state value and re-rendering to display a new quote on the ...

Is React Context suitable for use with containers too?

React provides an explanation for the use of Context feature Context in React allows data sharing that can be seen as "global" within a tree of components, like the authenticated user, theme, or language preference. Although this concept works well for ...

Accessing JS code from HTML is not possible in React

Attempting to create a list using React, I have utilized the module found here: https://github.com/pqx/react-ui-tree I am currently testing out the sample application provided in this link: https://github.com/pqx/react-ui-tree/blob/gh-pages/example/app.js ...

Every time I use Axios with NextJS, I keep getting a frustrating 405 method not allowed

I am facing a challenging issue with this... Currently, I am using NextJS for the frontend and making a request to <frontend-domain>/api/auth/register from here. const changePassword = async (currentPassword, password) => { await axios.post(& ...

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...

Is It Possible to Use Separate Stylesheets for Different Web Browsers?

I have been trying to implement a JavaScript code that loads a specific stylesheet based on the user's browser. However, it seems like the code is not functioning correctly as none of the stylesheets are being displayed. I have meticulously reviewed t ...

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

The property cannot be set for an undefined element in Jquery UI slider tabs

There seems to be some extra space at the bottom of the slider tabs between the navigators and content. Additionally, I am facing a challenge in making the page responsive as the content size does not adjust when I resize the window. To see the changes, I ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Executing Firebase Functions offline with secure connections (HTTPS)

I am facing an issue with CORS between my React app served over HTTPS (required for a service worker) and my backend running locally with Firebase Functions. My backend, which is a wrapper for an Express application with the CORS module enabled, is respon ...

In the event that the $state cannot be located, redirect to a different URL using Ui

Our platform is a unique combination of WordPress backend and AngularJS frontend, utilizing ui.router with html5 mode turned on and a base href="/" due to the stack sites being in the root of the site. We are currently facing an issue: 1) Previously, whe ...

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

I am having trouble with the CSS and Bootstrap not being applied after printing

Once the submit button is clicked on the initial output page, the CSS styling disappears and only a simple default form page is displayed. This does not meet my requirements. Using inline CSS allows it to work, but external CSS does not. Can someone please ...

Transforming a function into an array in TypeScript

I attempted to use the map() function on a dataURL array obtained from the usePersonList() hook, but I am struggling to convert my function to an array in order to avoid errors when clicking a button. import Axios from "axios"; import React, { us ...

What is the best way to transfer data between two app methods within an express.js framework?

Imagine having an app.js file like this: const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({ extended: true })); app.get("/login", (req, res ...

What is the best way to include an ajax request within a function and execute it only when needed?

I am working on an ajax request that fetches data from a specific URL. I have the following code snippet: $.ajax({ type: 'POST', url: '/get-result.php', dataType: 'json', data: 'pid=' + $(this).attr( ...