使用PassportJS和Node.js Google API库实现Google身份验证

3

我目前正在研究使用Node.js客户端来实现Google API:

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

我正在尝试使用护照进行身份验证,目前似乎已经起作用。

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);
    });
  }
  ));

在我的Google身份验证回调中:
app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {

    //do something here with the google api

  });

我可以获取req.user,其中包含accessToken
然而,Google api nodejs客户端的文档并没有清楚地说明如何使用accessToken。所提供的示例显示OAauth2Client检索令牌,但我想这部分已经在使用Passport时涵盖了吧?

是的,一旦 Passport 调用成功回调函数,它就已经成功并具有“profile”,因此我认为它已经完成了比较令牌或其他工作的所有工作。 - Plato
1个回答

5

我对 google-api-nodejs-client 不太熟悉,但是以下内容来自于它们的文档:

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

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

我假设你只需将凭证设置为 Passport 提供的凭证,事情就会顺利进行。

但是,说实话,我觉得这些 API 封装真的很牵强,建议直接使用 request。这样,您可以使用熟悉的模块从任何提供商访问任何 API 服务。


1
我确认,这个代码可以正常工作,只需执行以下操作:import google from 'googleapis'; const plus = google.plus('v1'); const oauth2Client = new google.auth.oauth2Client; - standup75

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接