'How do I properly set up Passport Google OAuth 2.0 with ExpressJS?

I am trying to set up some user authentication and want to use Google's OAuth2.0 to do so.

So far, I have set up a Google API Project at console.cloud.google.com and gotten an OAuth 2.0 Client ID and Client Secret (let's say clientID = 'myID.apps.googleusercontent.com' and clientSecret = 'mySecret'). Noodling around, I found that I should be using passport and I would like to use passport-google-oauth20 (Only because it has the most downloads, if there is something better PLEASE let me know). Following the instructions, I have:

.env.js

module.exports = {
    google: {
        clientID: 'myID.apps.googleusercontent.com',
        clientSecret: 'mySecret'
    }
}

app.js

const express = require('express')
const passport = require('passport')
const env = require('./.env.js')
const app = express()
const baseURL = 'https://api.mywebsite.com'

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

passport.use(new GoogleStrategy({
    clientID: env.google.clientID,
    clientSecret: env.google.clientSecret,
    callbackURL: baseURL + "/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    })
  }
))

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

app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/login'}), (req, res) => {
        // Successful authentication, redirect home.
        res.redirect('/');
    }
)

When I start the server and go to https://api.mywebsite.com/auth/google, I get redirected to https://accounts.google.com/signin/oauth/error?authError=some_mess&client_id=myID.apps.googleusercontent.com with an Error 400: redirect_uri_mismatch and referencing redirect_uri: http://127.0.0.1:5000/auth/undefined/auth/google/callback in the details. When I check the Google Console, I am explicitly allowing https://api.mywebsite.com in the Authorized JavaScript origins and all of https://api.mywebsite.com, https://api.mywebsite.com/auth/google/callback, and http://127.0.0.1:5000/auth/undefined/auth/google/callback in the Authorized redirect URIs.

How can I set this all up properly?

Bonus: If I wanted to run a validity check (say make sure the user is in a database), how could I do that?



Solution 1:[1]

You can set up google oauth2.0 properly in the following way:

const express = require('express')
const passport = require('passport')
const googleStrategy = require('passport-google-oauth20').Strategy;
const env = require('./.env.js')
const users =require('./../database/models/User'); //change this
const app = express()

//serialize user
passport.serializeUser((user,done)=>{
    done(null,user._id);
})

//deserialize user
//on the every request deserialize function checks user whether in database
passport.deserializeUser((id,done)=>{
    users.findOne({_id:new objectId(id)},(err,doc)=>{
        if(err){return done(err)};
        if(!doc){return done(null,false)}
        return done(null,doc);
    })
})

//GOOGLE STRATEGY
passport.use(new googleStrategy({
    clientID:  env.google.clientID,
    clientSecret:env.google.clientSecret,
    callbackURL:'https://api.mywebsite.com/auth/google/callback', //change this 
    passReqToCallback   : true
},function(request,accessToken, refreshToken, profile, callback){
    users.findOneAndUpdate({profile_id:profile.id},{ 
        $setOnInsert:{
            //your data that will insert when object is not found 
        }, 
        $set:{last_login:new Date() //if user exists update this field 
        //or something you want to update
    },{
        upsert:true, //if object didn't found, insert new object to db
        new:true //return updated data
    },(err,doc)=>{
        if(err){console.log(err)}
        return callback(null, doc);
    })
}))
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1