node.jspassport.jsgoogle-oauthpassport-google-oauth2

Passport + Google Token in Node + Express app keeps throwing 'Unauthorized' to attempts from Postman, token is good and manually verified


I have a backend REST API built with Node + Express + Passport and I'm trying to authenticate using a google access token. I am using this strategy.

I have looked through the package's documentation and issues on github but there was nothing that fixed the issue.

I have verified the access token against:

https://www.googleapis.com/oauth2/v1/tokeninfo?idToken with the id Token and https://www.googleapis.com/oauth2/v1/tokeninfo?acessToken with the access token and both are valid but none of them work. I have double-triple checked that I'm using the correct clientID and secret on the backend and on the frontend I get the token from.

Here's the relevant code:

    app.use(passport.initialize());
    passport.use(
      new GoogleTokenStrategy(
        {
          clientID: config.get('google.clientID'),
          clientSecret: config.get('google.clientSecret')
        },
        function(accessToken, refreshToken, profile, done) {

console.log(accessToken, refreshToken, profile, done)

          User.findOrCreate({ googleId: profile.id }, function(err, user) {
            return done(err, user);
          });
        }
      )
    );
    
    app.use('/user', passport.authenticate('google-token'), userRoute);

and I am importing at the top as follows:

const passport = require('passport');
const GoogleTokenStrategy = require('passport-google-token').Strategy;

The app isn't throwing out any kind of errors.

I added that console.log where the strategy is created -- when I fire from postman, there's NOTHING logged. When I'm firing from an angular frontend -- it logs the data and it is firing.


Solution

  • In my case this was being thrown because of the User.findOrCreate logic that I didn't even had defined. Facebook token passport package throws an internal server error because of that but the google one would just silently fail with no message.

    I will define my findOrCreate logic later down the development process. For now, this works for testing:

      new GoogleTokenStrategy(
        {
          clientID: config.get('google.clientID'),
          clientSecret: config.get('google.clientSecret')
        },
        function(accessToken, refreshToken, profile, done) {
          return done(null, profile);
        }
      )
    );