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

How do I keep a prompt at the bottom of the screen in C?

0  Asked on January 22, 2021 by wafwoof

 

URL query parameters to dict python

8  Asked on January 21, 2021 by leonardo-andrade

       

jQuery removeClass not working with draggable

1  Asked on January 21, 2021 by heila-al-mogren

     

How I can pass data between screens in React Native

2  Asked on January 21, 2021 by tuan-nguyen

   

Building a reference to a named column out of a passed vector

0  Asked on January 21, 2021 by sherman-sims

 

Splitting list into 2 parts, as equal to sum as possible

3  Asked on January 21, 2021 by jonathon

     

Camel router Builder with Java 6

0  Asked on January 21, 2021 by fiddle

   

Ask a Question

Get help from others!

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