I am pretty new in the world of NodeJS and my Javascript knowledge can be accurately described as noob+ . Don't laugh at me for failing at something (seemingly) this simple!
I've been trying for a couple of days to make a NodeJS backend support Google authorization using Passport.
The plan was to redirect the response to a certain page, but it doesn't work for some reason.
The relevant codes look like this:
const GOOGLE_CLIENT_ID = "...........................................";
const GOOGLE_CLIENT_SECRET = "..................";
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback"
},
function (token, tokenSecret, profile, done) {
console.log(profile.id);}
));
and
const express = require('express');
const cors = require('cors');
const passport = require('passport');
const router = express.Router();
const passportConfig = require('./Config/passport.config');
const blogapp = express();
blogapp.use(cors());
blogapp.use(express.static('public'));
blogapp.use(passport.initialize());
blogapp.use(passport.session());
blogapp.use(router);
.
.
.
.
.
.
blogapp.get('/auth/google',
passport.authenticate('google', {scope: ['https://www.googleapis.com/auth/plus.login' ]}));
blogapp.get( '/auth/google/callback',
passport.authenticate( 'google', {
successRedirect: '/',
failureRedirect: '/loginfailed'
}));
It successfully prints the profile.id, yet does not proceed to redirecting to the other pages. Another version of the relevant function was this:
blogapp.get('/auth/google/callback',
passport.authenticate('google', {failureRedirect: '/loginfailed'}),
(req, res) => {
res.redirect('/');
});
but did not work either.
I have also tried several versions of GoogleStrategy, including the ones returning a done(parameter1, parameter2), but nothing happens. It only prints the id, then stucks, and does not proceed to the next page.
What am I doing wrong?
Passport needs to know the user was authenticated successfully by using the done()
helper in the strategy callback.
function (token, tokenSecret, profile, done) {
console.log(profile.id);
done(null, profile);
}
More information on the verify callback and done
function:
http://www.passportjs.org/docs/configure/#verify-callback