Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PassportJS google authentication with the nodejs google api library

I'm currently looking at implementing a google api, using the nodejs client:

https://github.com/google/google-api-nodejs-client/

I'm trying to use passport in order to authenticate, which seems to be working@

passport.use(new GoogleStrategy({
  clientID: GOOGLE_CLIENT_ID,
  clientSecret: GOOGLE_CLIENT_SECRET,
  callbackURL: "http://localhost:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {

      var user = {
        id: profile.id,
        email: profile.email,
        firstName: profile.given_name,
        lastName: profile.family_name,
        accessToken: accessToken
      };

      return done(null, user);
    });
  }
  ));

In my google auth callback:

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {

    //do something here with the google api

  });

I can get hold of req.user, and this has the accessToken

However, the docs for the Google api nodejs client aren't clear on how to use an accessToken. The example included shows the OAauth2Client retrieving a token, but I guess that part has already been covered using Passport?

like image 654
Alex Avatar asked Jul 19 '26 01:07

Alex


1 Answers

I'm not familiar with google-api-nodejs-client, but this is in their documentation:

oauth2Client.credentials = {
  access_token: 'ACCESS TOKEN HERE',
  refresh_token: 'REFRESH TOKEN HERE'
};

client
  .plus.people.get({ userId: 'me' })
  .withAuthClient(oauth2Client)
  .execute(callback);

I assume you can just set the credentials to those provided by Passport, and things will work fine.

Honestly, though, I find these API wrappers really contrived, and recommend just using request. That way you can access any API service from any provider using a familiar module.

like image 95
Jared Hanson Avatar answered Jul 20 '26 20:07

Jared Hanson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!