Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TokenError: Bad Request; Google OAuth2; Passport.js on Node.js; Able to console.log data, however delivers error

I am attempting to use Passport.js to authorize Google OAuth2 on Node.js. I have tried all week to make it work and have no idea why it isn't, so am now resorting to stack for some potential help. I have tried all solutions to similar problems available on forums online.

Each time it sends the request it returns TokenError: Bad Request, however, it is able to console.log the required data, so this to me demonstrates that the token was in fact successful. I cannot explain why this is occurring.

I have tried being more specific in callback request e.g http://localhost:3000/auth/google/redirect. I have tried every other type of Oauth type google has Node server, web application, html ect. I have tried different ports.

AUTH ROUTES

 const router = require('express').Router();
 const passport = require('passport');

 // auth login
 router.get('/login', (req, res) => {
     res.render('login', { user: req.user });
 });

 // auth logout
 router.get('/logout', (req, res) => {
     // handle with passport
     res.send('logging out');
 });

 // auth with google+
 router.get('/google', passport.authenticate('google', {
     scope: ['profile']
 }));

 // callback route for google to redirect to
 // hand control to passport to use code to grab profile info
     router.get('/google/redirect', passport.authenticate('google'), 
   (req, 
   res) => {
      res.send('you reached the redirect URI');
   });

module.exports = router;

PASSPORT_SETUP

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('./keys');

passport.use(
new GoogleStrategy({
    // options for google strategy
    clientID: keys.google.clientID,
    clientSecret: keys.google.clientSecret,
    callbackURL: '/auth/google/redirect'
   }, (accessToken, refreshToken, profile, done) => {
    // passport callback function
    console.log('passport callback function fired:');
    console.log(profile);
    })
);

When submitted the process progresses through SignIn page, delivers desired result the console.log and then just sits for about 1 minute awaiting localhost.

As you can see the very thing it is trying to retrieve is already in the console.

console

It then progresses to throw and Error:

Error

like image 342
psquizzle Avatar asked Aug 13 '19 17:08

psquizzle


1 Answers

Sorry for the late reply, dug up some old code this is the point where it was marked as 'All auth methods functioning'. As stated by Aritra Chakraborty in the comments, "done" method was not being called. See the following implementation with Nedb.

const GoogleStrategy = require('passport-google-oauth20').Strategy;
const Datastore = require('nedb');
const database = new Datastore('database.db');
database.loadDatabase();

passport.serializeUser((user, done) => {
    done(null, user.googleId || user.id);
});

passport.deserializeUser((googleId, done) => {
    database.findOne({ googleId : googleId }, (err, user) => {
        done(null, user);
    });
});

var strategy = new GoogleStrategy({
    // options for google strategy
    clientID: keys.google.clientID,
    clientSecret: keys.google.clientSecret,
    callbackURL: '/auth/google/redirect'
}, (accessToken, refreshToken, object0, profile, done) => {
    // check if user already exists in our own db
    database.findOne({ googleId: profile.id }, (err, currentUser) => {
        if (currentUser !== null) {
            done(null, currentUser);
        } else {
            var d = new Date();
            var n = d.getTime();
            var duoID = uuidv1();
            var User = {
                duoVocalID: duoID,
                googleId: profile.id,
                username: profile.displayName,
                thumbnail: profile._json.image.url,
                oscope: object0.scope,
                oaccess_token: object0.access_token,
                otoken_type: object0.token_type,
                oid_token: object0.id_token,
                oexpires_in: object0.expires_in,
                oemails: profile.emails,
                olanguage: profile._json.language,
                oname: profile.name,
                TimeOfLastLogon: n,
                RefreshToken: refreshToken
            };
          
            database.insert(User, (err, newUser) => { });
            var newUser = User;
            done(null, newUser);
        }
    });
});

passport.use(strategy);

// auth with google+
app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile', 'email', 'https://www.googleapis.com/auth/spreadsheets'],
    accessType: 'offline', 
    approvalPrompt: 'force' 
}));

// callback route for google to redirect to
// hand control to passport to use code to grab profile info
app.get('/auth/google/redirect', passport.authenticate('google'), async (req, res) => {
    var userString = JSON.stringify(req.user)
    jwt.sign({userString}, 'secretKey', { expiresIn: '365d' }, (err, token) => {
        res.send("<script>localStorage.setItem('token', '"+token+"'); window.close(); window.opener.document.getElementById('modal-toggle').checked = false;</script>");
    });
});
like image 137
psquizzle Avatar answered Nov 04 '22 06:11

psquizzle