node.jsexpresspassport.jsgoogle-oauthpassport-google-oauth2

Can't get to google login page with passport and google oauth strategy


I'm trying to use Passport to have users be able to log in to a web app with with their Google account, but I can't seem to get my login route, /auth/google, to even redirect to the Google login page. My other routes work and I'm not getting any errors in my console, but when I go to localhost:5000/auth/google, the page just hangs and eventually gives a "localhost refused to connect" error (I'm assuming after it's timed out).

Any idea what could be going on? I've used basically exactly the same code successfully in another app - I know I haven't set up most of the scaffolding for full login, but I think it should at least be loading the google login page at this point.

index.js

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import passport from 'passport';
const GoogleStrategy = require('passport-google-oauth20').Strategy;

// import database from './server/src/models';
import userRoutes from './server/routes/UserRoutes';

const PORT = process.env.PORT | 5000;
const app = express();

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.googleClientID,
      clientSecret: process.env.googleClientSecret,
      callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, cb) => {
      console.log(accessToken);
    }
  )
);

app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
  res.send('Hello world!');
});

app.get('/auth/google', (req, res) => {
  passport.authenticate('google', {
    scope: ['profile', 'email']
  });
});

app.use('/users', userRoutes);

app.listen(PORT, () => {
  console.log(`App up on port ${PORT}`);
});

export default app;

here's a link to the full repo: https://github.com/olliebeannn/chatterpod


Solution

  • Figured it out - really stupid mistake. This:

    app.get('/auth/google', (req, res) => {
      passport.authenticate('google', {
        scope: ['profile', 'email']
      });
    });
    

    should be:

    app.get('/auth/google', 
      passport.authenticate('google', {
        scope: ['profile', 'email']
      })
    );