AnswerBun.com

Passport Google Oauth does not redirect to successful route upon login

Stack Overflow Asked by C-likethis123 on October 23, 2020

I’m trying to follow this tutorial to set up Google Oauth in my Express app using Passport.js.

Here are my routes, defined in a server.js file:

const passport = require("passport");
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");
require("./passport-setup");
app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());
app.use(
  cookieSession({
    name: "tuto-session",
    keys: ["key1", "key2"],
  })
);
app.use(passport.initialize()); //initialises passport js and auth process
app.use(passport.session()); //manage using sessions

const isLoggedIn = (req, res, next) => {
  if (req.user) {
    next();
  } else {
    res.sendStatus(401);
  }
};

app.get("/", (req, res) => res.send("Hello World! You're not logged in "));
// 1. You send your users to /google. This opens a google page, in passport-setup.js.
app.get(
  "/google",
  passport.authenticate("google", {
    scope: ["profile", "email"],
  })
);

app.get("auth/google/callback",
  passport.authenticate("google", { 
    successRedirect: '/good', 
    failureRedirect: "/failed" 
  }),
  function (req, res) {
    res.redirect("http://localhost:19006/good");
  }
);

app.get("/failed", (req, res) => res.send("You failed to log in!"));

app.get("/good", isLoggedIn, (req, res) =>
  res.send(`You logged in! Welcome ${req.user.email}`)
);

app.get("/logout", (req, res) => {
  req.session = null; // destroy session
  req.logout(); //logout from passport
  res.redirect("/"); //redirect to home.
});
app.listen(19006, () => console.log("Listening on port"));

server.js also imports passport-setup.js, where I stored the following configurations:

const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
// it will take the user, and take user.id. This makes the user smaller. Each time I'm directed to a route, will take the cookie in the session, go to deserializeUser 
passport.serializeUser(function (user, done) {
  console.log("serialise user")
  done(null, user)
})

// this function takes the id, returns the user object.
passport.deserializeUser(function (user, done) {
  console.log("deserialise user")
  //User.findById(id, function (err, user) {
  done(null, user)
  //})
  // so we will have the user in req.user. But for the purpose of this tutorial, no db.
})
// this /google page will take clientID, client secret to authenticate.
passport.use(new GoogleStrategy({
  clientID: 'MY_CLIENT_ID',
  clientSecret: 'MY_CLIENT_SECRET',
  callbackURL: "http://localhost:19006/auth/google/callback",
  passReqToCallback: true,
},
  function (accessToken, refreshToken, profile, done) {
      return done(null, profile)
  }
))

When I start up my app, I go to localhost:19006/google, which redirects me to the Google Oauth’s login page. However I get redirected to this link: http://localhost:19006/auth/google/callback?code=4%2F3AGyrRpoCivQNr2-7sXZDQETVzNi9JvxaOORhTmaAZoQjIHNPAf8nWqgBFkzrVprwhUF4qMo40ljxiGZLsBLn7U&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=0&prompt=consent#

I also get a 404 error code, with the page showing "Cannot GET /auth/google/callback".

I checked the express routes and I have defined that route, so I don’t get why the app is not showing this page.
I tried adding console.log messages to the following function:

// this /google page will take clientID, client secret to authenticate.
passport.use(new GoogleStrategy({
  clientID: 'MY_CLIENT_ID',
  clientSecret: 'MY_CLIENT_SECRET',
  callbackURL: "http://localhost:19006/auth/google/callback",
  passReqToCallback: true,
},
  function (accessToken, refreshToken, profile, done) {
   //added a console.log here
      return done(null, profile)
  }

app.get("/", (req, res) => res.send("Hello World! You're not logged in "));
// 1. You send your users to /google. This opens a google page, in passport-setup.js.
app.get(
  "/google",
  passport.authenticate("google", {
    scope: ["profile", "email"],
  })
);

app.get("auth/google/callback",
  passport.authenticate("google", { 
    successRedirect: '/good', 
    failureRedirect: "/failed" 
  }),
  function (req, res) {
// added console.log here
    res.redirect("http://localhost:19006/good");
  }
);

But my console did not end up logging anything.

What I have tried

In Google Developer Console, I set up the Client ID for web application with the following fields:
Image of credentials

I have tried replacing localhost with 127.0.0.1 in both the routes in my code and the Google Developer Screen, but it doesn’t work.

Add your own answers!

Related Questions

“Live” data capable alternative for Google Earth KML

1  Asked on February 15, 2021 by christoph1197

   

React component dispatching generic payload

1  Asked on February 14, 2021 by andyroo

   

CSS animted gradient

1  Asked on February 14, 2021

     

Running a value through an array of functions

2  Asked on February 14, 2021 by lars-holdaas

   

How to revert back to python 2.7?

1  Asked on February 14, 2021 by nikhil-shrivastava

         

Using same name for attribute and getter

1  Asked on February 13, 2021 by janpeterka

     

What is the purpose to use className beside functionName using colon(:)

1  Asked on February 13, 2021 by mahedi-hasan-durjoy

 

Python: access a variable in a module from another file

2  Asked on February 13, 2021 by yeroduk

 

How to get elements of a sublist in Java

5  Asked on February 13, 2021 by alvira

     

`SyntaxError` in if-else one-liner

2  Asked on February 13, 2021 by evgeniy-golovin

         

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP